Write a PHP code to check whether a number is palindrome or not. In this tutorial, we are going to write a PHP program to check whether an input number is palindrome or not.
What is a Palindrome Number?
Palindrome number is a number which remains the same when it’s digits are reversed.
For example – 121 is a palindrome number. If you reverse this number the number remains same. Let’s take another number 123. It’s not a palindrome number. If you reverse 123 it becomes 321.
PHP Code to Check Whether a Number is Palindrome or Not
How to check whether a number is palindrome or not in PHP. So, First reverse a number and compare this number with original number. If both the numbers are same then it’s a palindrome.
Logic –
i) Take a number.
ii) Reverse the input number.
iii) Compare both the numbers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
/* Take a number as an input and return it's reverse. */ function isPalindrome($num){ $inpt = $num; $sum = 0; /* Logic to reverse a number */ while(floor($inpt)) { $newnum = $inpt % 10; $sum = $sum * 10 + $newnum; $inpt = $inpt/10; } /* If input number and reverse of this number is same then it's a Palindrome. */ if($num == $sum){ return true; } else { return false; } } $input = 121; if(isPalindrome) { echo "Palindrome number"; } else { echo "Not a palindrome number"; } |