PHP program to verify whether given number or string is Palindrome or not

In this PHP tutorial, you are going to learn how to write a PHP program to verify whether a given number or string is a palindrome or not.

To verify whether a given number is Palindrome or not in PHP

A palindrome is a word, number or other sequences of characters which reads the same from backwards and forwards, for instance, take 1221 it is read the same when we start from any of the end its end being the same number.

Some examples are : 234432, 12321, 1234321, mom ,mam etc..

In this tutorial, we are going to deal with both alphabetical and numerical values.

To find whether the given string is a Palindrome or not we use strrev( ) function which is an inbuilt string function.

Here we treat every input as a string and reverse and compare them if both are same its a Palindrome else it is not a Palindrome.

Algorithm to check palindrome

  • First, we have to create an HTML code to accept input as we can’t accept input directly by PHP.
  • Open PHP by using <?php.
  • Create variables to store values which are sent from html code let it be “num”.
  • Now call the strrev function with parameter as num and store it in a variable let be “reverse”.
  • Create an if condition such that if both the “num” and “reverse” are the same .
  • If both are same then print “its a palindrome”, Else print “not a palindrome”.
  • That’s it our program is ready to execute.

Program:

<html>
<body>
<form method="post">        
Enter a Number/String: <input type="text" name="num"/><br>  
<button type="submit">Check</button>  
</form>  
</body>

</html>

<?php   
    if($_POST)  
    {  
        //get the value from form  
        $num = $_POST['num'];  
        //reversing the number  
        $reverse = strrev($num);  
          
        //checking if the number and reverse is equal  
        if($num == $reverse){  
            echo "The number/string $num is Palindrome";     
        }else{  
            echo "The number/string $num is not a Palindrome";   
        }  
}     
      ?>

Output:

Enter a Number/String: 12321
{submit}
//after clicking submit 
The number/string 12321 is a palindrome

You can also read:

Compress and create a zip file in PHP

How to generate random string in PHP?

Leave a Reply

Your email address will not be published. Required fields are marked *