PHP program to check for Anagram
An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. To check for anagrams in PHP, remove spaces, convert to lowercase, sort characters, and compare the sorted strings or arrays.
Examples
Input : "anagram", "nagaram"
Output : yes
Input : "mat", "fat"
Output : no
We use the below-inbuilt function to solve this problem:
Table of Content
Using count_chars()
The count_chars() function analyzes the frequency of each character in a string. By comparing the frequency arrays of both strings, we can determine if they are anagrams.
Example : In this example we check if two strings are anagrams by comparing their character counts. If the counts match, the strings are anagrams. The example checks "program" vs "grampro" and "card" vs "cart".
// PHP code to check a given string is an anagram
// of another or not
<?php
function is_anagram($string_1, $string_2)
{
if (count_chars($string_1, 1) == count_chars($string_2, 1))
return 'yes';
else
return 'no';
}
// Driver code
print_r(is_anagram('program', 'grampro')."\n");
print_r(is_anagram('card', 'cart')."\n");
?>
Output:
yes
no
Time Complexity: O(n) where n is the size of the string.
Using Character sorting
To check if two strings are anagrams in PHP, normalize by removing spaces and converting to lowercase, then sort and compare their character arrays. Return true if sorted arrays match, else false.
Example: In this example we check if two strings are anagrams by removing spaces, converting to lowercase, sorting characters, and comparing sorted arrays. It verifies "Listen" and "Silent" as anagrams.
<?php
function areAnagrams($str1, $str2)
{
// Remove spaces and convert to lowercase
$str1 = strtolower(str_replace(" ", "", $str1));
$str2 = strtolower(str_replace(" ", "", $str2));
// Check if lengths are different
if (strlen($str1) !== strlen($str2)) {
return false;
}
// Sort characters and compare
$sortedStr1 = str_split($str1);
$sortedStr2 = str_split($str2);
sort($sortedStr1);
sort($sortedStr2);
// Compare sorted arrays
return $sortedStr1 === $sortedStr2;
}
// Example usage
$string1 = "Listen";
$string2 = "Silent";
if (areAnagrams($string1, $string2)) {
echo "$string1 and $string2 are anagrams.";
} else {
echo "$string1 and $string2 are not anagrams.";
}
?>
Output
Listen and Silent are anagrams.
Using Character Frequency Arrays
This approach uses arrays to count the frequency of each character in both strings and compares these arrays.
Example: The PHP function areAnagrams checks if two strings are anagrams by comparing character frequencies after removing spaces and converting to lowercase. It then prints whether they are anagrams or not.
<?php
function areAnagrams($str1, $str2) {
// Remove whitespace and convert to lowercase
$str1 = strtolower(str_replace(' ', '', $str1));
$str2 = strtolower(str_replace(' ', '', $str2));
// Check lengths first
if (strlen($str1) != strlen($str2)) {
return false;
}
// Initialize arrays to store character frequencies
$count1 = array_fill(0, 26, 0);
$count2 = array_fill(0, 26, 0);
// Count frequencies of characters in both strings
for ($i = 0; $i < strlen($str1); $i++) {
$count1[ord($str1[$i]) - ord('a')]++;
$count2[ord($str2[$i]) - ord('a')]++;
}
// Compare character counts
for ($i = 0; $i < 26; $i++) {
if ($count1[$i] != $count2[$i]) {
return false;
}
}
return true;
}
// Example usage:
$string1 = "Listen";
$string2 = "Silent";
if (areAnagrams($string1, $string2)) {
echo "$string1 and $string2 are anagrams.";
} else {
echo "$string1 and $string2 are not anagrams.";
}
?>
Output
Listen and Silent are anagrams.
Using Hash Maps
Normalize strings by removing spaces and converting to lowercase. Create hash maps to store character frequencies for each string. Compare these maps: if they match, the strings are anagrams. This method ensures accurate character count comparison.
Example:
<?php
function areAnagrams($str1, $str2) {
$str1 = strtolower(str_replace(' ', '', $str1));
$str2 = strtolower(str_replace(' ', '', $str2));
if (strlen($str1) !== strlen($str2)) {
return "no";
}
$hashMap1 = [];
$hashMap2 = [];
for ($i = 0; $i < strlen($str1); $i++) {
$char1 = $str1[$i];
$char2 = $str2[$i];
$hashMap1[$char1] = ($hashMap1[$char1] ?? 0) + 1;
$hashMap2[$char2] = ($hashMap2[$char2] ?? 0) + 1;
}
return $hashMap1 == $hashMap2 ? "yes" : "no";
}
echo areAnagrams("Listen", "Silent") . PHP_EOL; // Output: yes
echo areAnagrams("mat", "fat") . PHP_EOL; // Output: no
?>
Output
yes no
Using XOR Bitwise Operator
This method leverages the XOR bitwise operator to determine if two strings are anagrams. The idea is based on the fact that if two strings have the same characters with the same frequency, XORing all the characters in both strings together will yield zero.
Example
The following PHP function areAnagramsXOR() checks if two strings are anagrams by XORing all characters in both strings. If the final XOR value is 0 and the lengths are the same, the strings are anagrams.
<?php
function areAnagramsXOR($str1, $str2) {
// Remove whitespace and convert to lowercase
$str1 = strtolower(str_replace(' ', '', $str1));
$str2 = strtolower(str_replace(' ', '', $str2));
// If lengths differ, they cannot be anagrams
if (strlen($str1) !== strlen($str2)) {
return "no";
}
$xor = 0;
// XOR all characters in both strings
for ($i = 0; $i < strlen($str1); $i++) {
$xor ^= ord($str1[$i]);
$xor ^= ord($str2[$i]);
}
// If the final XOR is 0, strings are anagrams
return $xor === 0 ? "yes" : "no";
}
// Example usage:
echo areAnagramsXOR("Listen", "Silent") . PHP_EOL; // Output: yes
echo areAnagramsXOR("mat", "fat") . PHP_EOL; // Output: no
?>
Output
yes no