PHP Program to Check Palindrome Number
strrev(), and comparing it to the original string; for example, $isPalindrome = ($num == strrev((string)$num));.Examples
How to Think About It
Algorithm
Code
<?php $num = 121; $strNum = (string)$num; $revStrNum = strrev($strNum); if ($strNum === $revStrNum) { echo "$num is a palindrome number."; } else { echo "$num is not a palindrome number."; } ?>
Dry Run
Let's trace the number 121 through the code to see how it checks for palindrome.
Input number
num = 121
Convert to string
strNum = "121"
Reverse string
revStrNum = "121"
Compare strings
"121" === "121" is true
Output result
Print '121 is a palindrome number.'
| Step | strNum | revStrNum | Comparison Result |
|---|---|---|---|
| 1 | 121 | 121 | true |
Why This Works
Step 1: Convert number to string
We convert the number to a string so we can easily reverse it using string functions.
Step 2: Reverse the string
Using strrev(), we reverse the string to check if it reads the same backwards.
Step 3: Compare original and reversed
If the reversed string matches the original, the number is a palindrome.
Alternative Approaches
<?php $num = 121; $original = $num; $reverse = 0; while ($num > 0) { $digit = $num % 10; $reverse = $reverse * 10 + $digit; $num = (int)($num / 10); } if ($original === $reverse) { echo "$original is a palindrome number."; } else { echo "$original is not a palindrome number."; } ?>
<?php function isPalindromeStr($str) { if (strlen($str) <= 1) return true; if ($str[0] !== $str[strlen($str) - 1]) return false; return isPalindromeStr(substr($str, 1, -1)); } $num = 121; if (isPalindromeStr((string)$num)) { echo "$num is a palindrome number."; } else { echo "$num is not a palindrome number."; } ?>
Complexity: O(n) time, O(n) space
Time Complexity
The time depends on the length of the number's string form, as reversing and comparing take linear time.
Space Complexity
Extra space is used to store the string and its reversed copy, so space is linear in the number of digits.
Which Approach is Fastest?
The arithmetic method avoids string conversion and uses constant space, making it faster and more memory efficient for large numbers.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String reverse | O(n) | O(n) | Simple and readable code |
| Arithmetic reverse | O(n) | O(1) | Performance with large numbers |
| Recursive string check | O(n) | O(n) | Learning recursion, less efficient |