PHP Tutorial

PHP Examples

PHP Practice

PHP program to check whether given number is palindrome or not

Here, we are implementing a PHP program that will check whether a given integer number is palindrome or not. By IncludeHelp Last updated : December 09, 2023

Problem statement

Given a number and we have to check whether it is palindrome or not using PHP program.

What is Palindrome number?

A number which is equal to its reverse number is said to be a palindrome number.

Example

The sample input and output for checking Palindrome number.

Input:
Number: 12321

Output:
It is palindrome number

Explanation:
Number is 12321 and its reverse number is 12321, 
both are equal. Hence, it is a palindrome number.

Steps/Algorithm for Checking Palindrome Number

The following are the steps to check whether given number is in a Palindrome number or not:

  • Assign the given number to a temporary variable, so that it can be used for comparing with the reverse number.
  • Take a variable to store sum (i.e., reverse number)
  • By using the while loop, extract the last digit of the number, use this number in the expression ($sum = $sum * 10 + $digit;) to make it reverse. And, then divide the number by 10. Repeat this step until the value is temporary number is zero.
  • For checking the Palindrome number, compare the sum (reverse number) with the original (given) number.

PHP code to check palindrome number

<?php
//function: isPalindrome
//description
function isPalindrome($number)
{
    //assign number to temp variable
    $temp = $number;
    //variable 'sum' to store reverse number
    $sum = 0;

    //loop that will extract digits from the last
    //to make reverse number
    while (floor($temp)) {
        $digit = $temp % 10;
        $sum = $sum * 10 + $digit;
        $temp = $temp / 10;
    }
    //if number is equal to its reverse number
    //then it will be a palindrome number
    if ($sum == $number) {
        return 1;
    } else {
        return 0;
    }
}

//Main code to test above function
$num = 12321;
if (isPalindrome($num)) {
    echo $num . " is a palindrome number";
} else {
    echo $num . " is not a palindrome number";
}
?>

Output

12321 is a palindrome number

The following PHP topics are used in the above examples:

PHP Basic Programs »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.