How to Make String Palindrome in PHP

Scotty Moe

How to Make String Palindrome: A string is said to be Palindrome, if its reverse string is the same as it is!.

Let suppose we have a string = “TAT ” now if we reverse it !

it will still be TAT. so we simply say that the string is palindrome.Lets look at the simple example to understand all this.


<?php

$str = "tat";
$reverse_str= strrev($str);
if( $reverse_str == $str){

echo"the string ".$str."is Palindrome";
}
else
{
echo"the string ".$str."is not Palindrome";
}
?>

 

Now lets try the same Palindrome without using strrev() function.

Palindrome without using strrev() function in php

<?php

$str = “level”;
$str_array = str_split($str);
$str_reverse =””;
$size = count($str_array);
echo”the size of string is “.$size;

for($i=$size-1; $i>=0;$i–){

$str_reverse.=$str_array[$i];

}
if($str_reverse == $str){

echo “this is Palindrome”;}

else{
echo “this is not Palindrome”;
}

?>

Please do post your comments .

 

3 thoughts on “How to Make String Palindrome in PHP”

  1. I think this code does not work, if we change the last word to capital letter “T”. Probably it will show an error. Probably we need to change these line of code. See below.

    $reverse_str= strcasecmp(strrev($str), $str );

    Reply

Leave a Comment