![]() |
VOOZH | about |
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
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".
Output:
yes
no
Time Complexity: O(n) where n is the size of the string.
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.
Listen and Silent are anagrams.
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.
Listen and Silent are anagrams.
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:
yes no
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.
yes no