VOOZH about

URL: https://www.geeksforgeeks.org/php/php-program-check-anagram/

⇱ PHP program to check for Anagram - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

PHP program to check for Anagram

Last Updated : 14 Aug, 2024

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:

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".

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.


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.


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:


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.


Output
yes
no
Comment
Article Tags: