
Standard Palindrome in PHP
A palindrome is a word or phrase that reads the same forwards and backwards, ignoring spaces and punctuation. “Racecar”, “level”, and “A man a plan a canal Panama” are all palindromes.
Checking for one is a classic PHP exercise. In this post, I’ll show you a function that checks strings, how it works, and how to check numbers too. Let’s get into it.
The PHP Code
Since you’re likely here for the code, here’s the full function:
<?php
function isPalindrome(string $str): bool
{
$cleaned = strtolower(preg_replace('/[^A-Za-z0-9]/', '', $str));
return $cleaned !== '' && $cleaned === strrev($cleaned);
}
var_dump(isPalindrome("racecar")); // bool(true)
var_dump(isPalindrome("Madam I'm Adam")); // bool(true)
var_dump(isPalindrome("A man a plan a canal Panama")); // bool(true)
var_dump(isPalindrome("hello")); // bool(false)
It returns true or false, so you can drop it straight into an if:
<?php
$phrase = "Madam I'm Adam";
if (isPalindrome($phrase)) {
echo "$phrase is a palindrome";
} else {
echo "$phrase is not a palindrome";
}
How It Works
The function does three things before comparing:
- Strips non-alphanumeric characters:
preg_replaceremoves anything that isn’t a letter or number (spaces, apostrophes, punctuation). “Madam I’m Adam” becomes “MadamImAdam”. - Lowercases:
strtolowermakes the check case-insensitive. “MadamImAdam” becomes “madamimadam”. - Reverses and compares:
strrevflips the cleaned string, and===checks it matches exactly. “madamimadam” reversed is still “madamimadam”.
One thing worth knowing: the $cleaned !== '' check stops a string like “!!” from counting as a palindrome. Once the punctuation is stripped there’s nothing left to compare.
Palindrome Number in PHP
For numbers like 121 or 12321, the easiest way is to cast to a string and reuse the same function:
<?php
var_dump(isPalindrome((string) 12321)); // bool(true)
var_dump(isPalindrome((string) 123)); // bool(false)
If your assignment says not to use strings, reverse the digits with math instead:
<?php
function isPalindromeNumber(int $number): bool
{
if ($number < 0) {
return false;
}
$original = $number;
$reversed = 0;
while ($number > 0) {
$reversed = $reversed * 10 + $number % 10;
$number = intdiv($number, 10);
}
return $original === $reversed;
}
var_dump(isPalindromeNumber(12321)); // bool(true)
var_dump(isPalindromeNumber(123)); // bool(false)
var_dump(isPalindromeNumber(-121)); // bool(false)
Each loop takes the last digit off with % 10 and adds it to the end of $reversed. Negative numbers return false, since “-121” backwards is “121-”.
Find Palindromes in a Sentence
To pull every palindrome word out of a sentence, split it into words and run each one through isPalindrome():
<?php
$sentence = "Hannah has a racecar";
$found = array_filter(
explode(" ", $sentence),
fn($word) => mb_strlen($word) > 1 && isPalindrome($word)
);
print_r(array_values($found));
// Array ( [0] => Hannah [1] => racecar )
The mb_strlen($word) > 1 check skips single letters like “a”, which are technically palindromes but usually not what you want.
One limit to know: strrev works byte by byte, so it’s meant for plain English letters and numbers. That’s also why the regex strips everything else first.
If you work with PHP strings a lot, limiting text length in PHP is another handy snippet.
Slap a sticker on this post
Comments
Loading comments…