Thursday, December 18, 2025
HomeLanguagesPHP program to check for Anagram

PHP program to check for Anagram

We are given two strings, we need to check if strings are Anagram. Examples:

Input : "anagram", "nagaram"
Output : yes

Input : "mat", "fat"
Output : no

We use the below inbuilt function to solve this problem:

  • count_chars(): this function generally has syntax count_chars(string, return_mode) is use to perform several operations related to string. This parameter is optional. It takes value to 0, 1, 2, 3, 4.

The idea to solve this problem using the above mentioned function is, to use value 1 i.e. in this chosen mode the above function will return an array with key value pairs, where keys are ASCII values and corresponding values will be the number of occurrences of that ASCII value. The array possess only those keys as ASCII values whose frequency is more than 0. 

php




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

RELATED ARTICLES

Most Popular

Dominic
32455 POSTS0 COMMENTS
Milvus
108 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11958 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12037 POSTS0 COMMENTS
Shaida Kate Naidoo
6958 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6911 POSTS0 COMMENTS
Umr Jansen
6890 POSTS0 COMMENTS