PHP Anagram Check: Long & One-Liner Approach

Опубликовано: 06 Февраль 2026
на канале: CodeVisium
1,010
4

In this Code Quickies script by CodeVisium, we demonstrate two ways to check whether two strings are anagrams in PHP—a common challenge in coding interviews and algorithm practice. An anagram is created by rearranging the letters of a word or phrase to produce a new word or phrase using all the original letters exactly once. This script features both a detailed, step-by-step (Long Version) approach and a concise, elegant one-liner version that leverages PHP’s modern arrow functions.

Long Version Explanation:

Data Cleaning:

Both input strings are processed using preg_replace() to strip out any non-alphanumeric characters (such as punctuation or spaces) and then converted to lowercase using strtolower(). This normalization ensures that case or extraneous characters do not affect the anagram check.

Conversion to Array:

The cleaned strings are split into arrays of individual characters using str_split(). This is an essential step because sorting is performed on arrays.

Sorting:

Each character array is sorted using PHP’s sort() function. Sorting rearranges the characters in alphabetical order.

Comparison:

Finally, the sorted arrays are compared with the identity operator (===). If they are identical, the function returns true, indicating that the strings are anagrams; otherwise, it returns false.

One-Liner Version Explanation:

For the one-liner, we create a PHP arrow function that leverages a helper function sortedString() to accomplish the heavy lifting:

sortedString() cleans and sorts a string in one go.

The one-liner then simply compares the results from sortedString($str1) and sortedString($str2).

This concise method is powerful for quick checks and demonstrates modern PHP capabilities while retaining clarity.

Complete Code for Copy-Paste:

The full PHP script above includes both approaches, allowing you to test the anagram check by simply copying the code into your PHP environment. Experiment with different string values to see how the algorithm performs!

#PHP #Anagram #CodingShorties #CodeVisium #StringManipulation #Algorithm #InterviewPrep #TechTutorial #CodeSnippet #ProgrammingTips

Codes:

V?php
// Long Version: Check if two strings are anagrams in a detailed way.
function isAnagramLong($str1, $str2) {
// Step 1: Remove non-alphanumeric characters and convert strings to lowercase.
$s1 = strtolower(preg_replace('/\W+/', '', $str1));
$s2 = strtolower(preg_replace('/\W+/', '', $str2));

// Step 2: Convert cleaned strings to arrays of characters.
$arr1 = str_split($s1);
$arr2 = str_split($s2);

// Step 3: Sort both arrays.
sort($arr1);
sort($arr2);

// Step 4: Compare the sorted arrays.
return $arr1 === $arr2;
}

// Helper function to clean and sort a string.
// Returns the sorted string which is used in the one-liner.
function sortedString($str) {
$clean = strtolower(preg_replace('/\W+/', '', $str));
$arr = str_split($clean);
sort($arr);
return implode('', $arr);
}

// One-Liner Version: Using an arrow function with the helper function.
$isAnagramOneLiner = fn($str1, $str2) =v sortedString($str1) === sortedString($str2);

// Testing the functions.
$str1 = "Listen";
$str2 = "Silent";

echo "Input Strings: \"$str1\" and \"$str2\"\n";
echo "Anagram Check (Long Version): " . (isAnagramLong($str1, $str2) ? 'True' : 'False') . "\n";
echo "Anagram Check (One-Liner): " . ($isAnagramOneLiner($str1, $str2) ? 'True' : 'False') . "\n";
?v