Check whether a number or string is a palindrome in PHP
A palindrome reads the same forwards and backwards. The digits of 12321 form a palindrome. The word “Madam” also qualifies if you ignore letter case. Decide how to handle case, punctuation, and spaces before comparing text.
A simple example
Compare a word with its reverse
Start withaba
Do thisRead from the other end
Resultaba
Compare the outside letters first. Both are a, and the middle letter stays b.
Check a reversible locker code
Start withCode 1221
Do thisRead the digits backwards
Result1221 matches
A locker-code checker can flag codes that read the same from either end. With code 1231 the reverse is 1321, so it fails.
Integer Palindrome
String Palindrome
Check a decimal integer
For a nonnegative integer, repeatedly take the last decimal digit and build the reverse. Compare it with the original number. In fixed-width types, check that the reversed value fits.
PHP source code
<?php
class PalindromeExample {
public function checkPalindrome() {
$originalNumber = 12321;
$reverseNumber = 0;
$temp = $originalNumber;
while ($temp > 0) {
$remainder = $temp % 10;
$reverseNumber = ($reverseNumber * 10) + $remainder;
$temp = (int)($temp / 10);
}
if ($originalNumber == $reverseNumber) {
echo("The given number is a palindrome");
} else {
echo("The given number is not a palindrome");
}
}
}
$obj = new PalindromeExample();
$obj->checkPalindrome();
Output
The given number is a palindrome
Advertisements
Check a word
For this word, compare the original letters with their reverse using the same case on both sides. These examples use ASCII text.
PHP source code
<?php
class PalindromeExample {
public function checkPalindrome() {
$originalString = "Madam";
$reverseString = "";
$length = strlen($originalString);
for($i = $length - 1; $i >= 0; $i --) {
$reverseString = $reverseString . $originalString[$i];
}
// Case in-sensitive comparision
if (strtolower($originalString) == strtolower($reverseString)) {
echo("The given string is a palindrome");
} else {
echo("The given string is not a palindrome");
}
}
}
$obj = new PalindromeExample();
$obj->checkPalindrome();