0
0
PhpProgramBeginner · 2 min read

PHP Program to Check Anagram with Example

To check an anagram in PHP, use strtolower to ignore case, then sort the characters of both strings with str_split and sort, and finally compare them with ==.
📋

Examples

Inputlisten, silent
OutputThe strings are anagrams.
Inputhello, world
OutputThe strings are not anagrams.
InputDormitory, Dirty room
OutputThe strings are anagrams.
🧠

How to Think About It

To check if two words are anagrams, first make them lowercase to ignore case differences. Then, split each word into letters, sort these letters alphabetically, and compare the sorted results. If they match exactly, the words are anagrams because they have the same letters in the same amounts.
📐

Algorithm

1
Get two input strings.
2
Convert both strings to lowercase.
3
Remove spaces from both strings.
4
Split each string into an array of characters.
5
Sort both arrays alphabetically.
6
Compare the sorted arrays; if equal, return true (anagrams), else false.
💻

Code

php
<?php
function areAnagrams(string $str1, string $str2): bool {
    $str1 = strtolower(str_replace(' ', '', $str1));
    $str2 = strtolower(str_replace(' ', '', $str2));
    $arr1 = str_split($str1);
    $arr2 = str_split($str2);
    sort($arr1);
    sort($arr2);
    return $arr1 == $arr2;
}

// Example usage
$str1 = "listen";
$str2 = "silent";
if (areAnagrams($str1, $str2)) {
    echo "The strings are anagrams.";
} else {
    echo "The strings are not anagrams.";
}
Output
The strings are anagrams.
🔍

Dry Run

Let's trace the example 'listen' and 'silent' through the code.

1

Convert to lowercase and remove spaces

'listen' -> 'listen', 'silent' -> 'silent'

2

Split strings into arrays

'listen' -> ['l','i','s','t','e','n'], 'silent' -> ['s','i','l','e','n','t']

3

Sort both arrays

['l','i','s','t','e','n'] -> ['e','i','l','n','s','t'], ['s','i','l','e','n','t'] -> ['e','i','l','n','s','t']

4

Compare sorted arrays

Both arrays are equal, so return true.

StepString 1 ArrayString 2 Array
Initial split['l','i','s','t','e','n']['s','i','l','e','n','t']
After sort['e','i','l','n','s','t']['e','i','l','n','s','t']
💡

Why This Works

Step 1: Normalize strings

Using strtolower and str_replace makes sure case and spaces don't affect the comparison.

Step 2: Sort characters

Sorting the characters puts them in order so we can easily compare if both strings have the same letters.

Step 3: Compare arrays

If the sorted arrays are exactly the same, the strings are anagrams because they contain the same letters.

🔄

Alternative Approaches

Count characters using associative arrays
php
<?php
function areAnagramsCount(string $str1, string $str2): bool {
    $str1 = strtolower(str_replace(' ', '', $str1));
    $str2 = strtolower(str_replace(' ', '', $str2));
    $count1 = count_chars($str1, 1);
    $count2 = count_chars($str2, 1);
    return $count1 == $count2;
}

// Usage
if (areAnagramsCount('Dormitory', 'Dirty room')) {
    echo "The strings are anagrams.";
} else {
    echo "The strings are not anagrams.";
}
This method counts how many times each character appears, which can be faster for long strings but uses more memory.
Using sorting with multibyte support
php
<?php
function areAnagramsMultibyte(string $str1, string $str2): bool {
    $str1 = mb_strtolower(str_replace(' ', '', $str1));
    $str2 = mb_strtolower(str_replace(' ', '', $str2));
    $arr1 = preg_split('//u', $str1, -1, PREG_SPLIT_NO_EMPTY);
    $arr2 = preg_split('//u', $str2, -1, PREG_SPLIT_NO_EMPTY);
    sort($arr1);
    sort($arr2);
    return $arr1 == $arr2;
}

// Usage
if (areAnagramsMultibyte('résumé', 'sérumé')) {
    echo "The strings are anagrams.";
} else {
    echo "The strings are not anagrams.";
}
This approach supports special characters and accents by using multibyte string functions.

Complexity: O(n log n) time, O(n) space

Time Complexity

Sorting the characters dominates the time cost, which is O(n log n) where n is the string length.

Space Complexity

Extra space is used to store character arrays, so space complexity is O(n).

Which Approach is Fastest?

Counting characters with associative arrays can be faster (O(n)) but uses more memory; sorting is simpler and good for short strings.

ApproachTimeSpaceBest For
Sorting charactersO(n log n)O(n)Simple and short strings
Counting charactersO(n)O(n)Long strings, performance sensitive
Multibyte sortingO(n log n)O(n)Strings with special characters
💡
Always remove spaces and convert to lowercase before checking anagrams to avoid false mismatches.
⚠️
Beginners often forget to normalize case or remove spaces, causing correct anagrams to fail the test.