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'>
$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 ";
   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 condition checking. Here is the change in if condition ( of above used code ) to make it case insensitive.

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.
$t1='racecar';  // sample string, change this data 
$length=strlen($t1); // length of the string
$t1_reverse=''; // to hold the revesed string
$t1_reverse .=$t1[$i];
echo "<i>$t1</i> is a Palindrome ";	
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.
$t1=$t2=1234321; // keeping in two variables 
	$d=$t1%10; // reminder of division 
	$t1_reverse = $t1_reverse * 10 + $d;
	$t1=floor($t1/10); // floor value
//echo $t1_reverse;

echo "<i>$t2</i> is a Palindrome ";	
echo "<i>$t2</i> is NOT a Palindrome ";		
1234321 is a Palindrome
Introduction to PHP Printing output by ECHO command
Basic Codes Armstrong number Fibonacci Series
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

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