Quickly Determine If Two Strings Are Anagrams in PHP

Quickly Determine If Two Strings Are Anagrams in PHP

When interviewing with tech companies, there are a LOT of questions involving anagrams. While there are many different approaches to solving these questions, here is a simple one-line function that can determine whether or not two strings are anagrams in PHP.

This approach utilizes the built-in PHP function, count_chars(). When using a double-equals (not a triple equals), we can compare the arrays returned by this function on both strings, and if they are anagrams, they will be equal.

<?php

function is_anagram($a, $b) {
	return(count_chars($a, 1) == count_chars($b, 1));
}
Show Comments