PHP Palindrome checking


madam, racecar, malayalam
are Palindromes
Enter any string

Checking string or number is Palindrome or not using PHP sticky form without strrev() functions

We used strrev() to reverse a string and then compare. We can use a form to post the string to the script. This is sticky form holding the value of user entered data. Here is the complete code.
<form method=POST action='' name=form1>
<input type=text name=t1 class='form-control' value='$t1' >
<input type=submit value='Check String'>
</form>
<?Php
$t1=$_POST['t1']; // Using POST method  of a FORM 
//$t1='madam'; // String variable with data for testing
if(strlen($t1) >0){
  if($t1==strrev($t1)){ // change this line  for case insensitive 
   echo "<i>$t1</i> is a Palindrome ";
  }else{
   echo "<i>$t1</i> is NOT a Palindrome ";
  }
}else{echo "Enter any string"; }
?>

case insensitive

We can use strtolower() function to convert all upper case chars to lower case char before using the if condtion checking. Here is the change in if condition ( of above used code ) to make it case insensitive.
if(strtolower($t1)==strtolower(strrev($t1))){

Without using strrev()

We can use for loop to read each char from the end of the string. The function strlen() returns the length of the string.
<?php
$t1='racecar';  // sample string, change this data 
$length=strlen($t1); // length of the string
$t1_reverse=''; // to hold the revesed string
for($i=$length-1;$i>=0;$i--){
$t1_reverse .=$t1[$i];
}
if($t1_reverse==$t1){
echo "<i>$t1</i> is a Palindrome ";	
}else{
echo "<i>$t1</i> is NOT a Palindrome ";		
}
?>

Using Numbers

We can get digits out of number and get the reverse number from the main number.
<?php
$t1=$t2=1234321; // keeping in two variables 
$t1_reverse=0; 
while($t1>0){
	$d=$t1%10; // reminder of division 
	$t1_reverse = $t1_reverse * 10 + $d;
	$t1=floor($t1/10); // floor value
}
//echo $t1_reverse;

if($t1_reverse==$t2){
echo "<i>$t2</i> is a Palindrome ";	
}else{
echo "<i>$t2</i> is NOT a Palindrome ";		
}
?>
Output
1234321 is a Palindrome
Introduction to PHP Printing output by ECHO command
Basic Codes Armstrong number Fibonacci Series

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer