PHP Program to check whether the two strings are anagram or not

What are anagram strings?

Anagram strings are two strings built up by the same set of characters, where the order of characters is the only difference in the strings. For example, the word 'silent' and 'listen' are anagrams, or 'peek' and 'keep' are anagrams.

How to check whether the two strings are anagrams or not using PHP?

In this program, we are accepting the strings from the user and checking that the strings are anagram or not. First, we have to sort the strings for that we have to convert the strings into an array and convert back them into strings and check these strings and if both are the same then they are anagrams otherwise they are not anagram strings. For these processes we are using certain built-in functions 

  • strlen() to find the length of the string 
  • strtolower() to convert the strings into lowercase

  • sort() to sort the array

  • implode() to convert the array into a string

ALGORITHM

Step 1: Accept the strings into the variables str1 and str2

Step 2: Assign these strings in the variables str1 and str2 into the variables s1 and s2

Step 3: Check the condition 'strlen(s1) != strlen(s2)' if true the print that the entered strings are not anagram and exit the program otherwise perform the following steps

Step 4: Convert the strings in the variables s1 and s2 into lowercase by using the built-in function strtolower() and assign it to the variables s1 and s2

Step 5: Convert the strings in the variables s1 and s2 into array by using the built-in function str_split() and assign it to the variables let1 and let2

Step 6: Sort the array let1 and let2 by using the built-in function sort()

Step 7: Convert the array let1 and let2 into the strings by using the built-in function implode()

Step 8: Check the condition 'strcmp(s1, s2) == 0' if true print that the entered strings are anagram otherwise print that the entered strings are not an anagram

PHP Source Code

                                          <?php
$str1 = readline("Enter the 1st string: ");
$str2 = readline("Enter the 2nd string: ");
$s1 = $str1;
$s2 = $str2;
if (strlen($s1) != strlen($s2)) {
    echo "The entered strings $str1 and $str2 are not anagram";
} else {
    $s1 = strtolower($s1);
    $s2 = strtolower($s2);
    $let1 = str_split($s1);
    $let2 = str_split($s2);
    sort($let1);
    sort($let2);
    $s1 = implode("", $let1);
    $s2 = implode("", $let2);
    if (strcmp($s1, $s2) == 0) {
        echo "The entered strings $str1 and $str2 are anagram";
    } else {
        echo "The entered strings $str1 and $str2 are not anagram";
    }
}
?>
                                      

OUTPUT

Example 1
Enter the 1st string: race
Enter the 2nd string: care
The entered strings race and care are anagram

Example 2
Enter the 1st string: earth
Enter the 2nd string: heart
The entered strings earth and heart are anagram