Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 64 / 68

Checking Whether Two Words Are Anagrams

In this lesson you will learn to decide whether two words are anagrams - related by rearranging their letters. This is for anyone searching for "PHP anagram check".

An anagram is a different word made from the same letters rearranged (for example, listen and silent). Sort the letters of both strings and see whether they match.

The sample code folds the case first and splits into character arrays with str_split(strtolower($a)) and str_split(strtolower($b)), then sorts both with sort() before comparing.

A common stumbling block for beginners is needing to unify the case with something like strtolower() when the comparison should ignore it. Compare without normalising and words that really are anagrams get reported as different.

For long strings, counting how often each character occurs is faster. It is a basic technique for comparing strings while ignoring order, and it even applies to simple code-breaking games.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)