PHP Program to check for Anagram

PHP (Hypertext Preprocessor) is a widely used server-side scripting language for web development. In PHP, you can check if two strings are anagrams by comparing their character frequencies using built-in functions.

What is an Anagram?

Anagrams are words or phrases formed by rearranging the letters of another word or phrase. In an anagram, all the original letters must be used exactly once, with no additional or missing letters.

For example, "listen" and "silent" are anagrams because they use the same letters rearranged in different order.

Using count_chars() Function

The count_chars() function is a built-in PHP function that returns information about character frequency in a string

Syntax

count_chars(string $string, int $return_mode = 0): mixed

Parameters

  • $string (required): The input string for which you want to count the characters.

  • $return_mode (optional): The return mode. Mode 1 returns an associative array where keys are ASCII values and values are character frequencies.

Example

Here's how to check for anagrams using count_chars() ?

<?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
echo is_anagram('stop', 'post') . "<br>";
echo is_anagram('card', 'cart') . "<br>";
echo is_anagram('listen', 'silent') . "<br>";
?>
yes
no
yes

How It Works

The function compares character frequencies of both strings using count_chars() with mode 1. This creates arrays where each character's ASCII value maps to its frequency count. If both arrays are identical, the strings are anagrams.

Alternative Method Using str_split() and sort()

Another approach is to split strings into character arrays and sort them ?

<?php
function is_anagram_sort($string_1, $string_2)
{
    $chars_1 = str_split(strtolower($string_1));
    $chars_2 = str_split(strtolower($string_2));
    
    sort($chars_1);
    sort($chars_2);
    
    return ($chars_1 === $chars_2) ? 'yes' : 'no';
}

echo is_anagram_sort('Stop', 'Post') . "<br>";
echo is_anagram_sort('Card', 'Cart') . "<br>";
?>
yes
no

Conclusion

PHP provides multiple ways to check for anagrams. The count_chars() method compares character frequencies, while the sorting method arranges characters alphabetically for comparison. Both approaches effectively determine if two strings are anagrams.

Updated on: 2026-03-15T10:36:05+05:30

920 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements