» What is Palindrome?
It is a word or phrase that is the same spelled forwards and backwards. Example: madam, level, Malayalam etc.
» Find string palindrome or not in PHP using strrev() function
<?php
$word = "level"; // declare a varibale
echo "String: " . $word . "<br>";
$reverse = strrev($word); // reverse the word
if ($word == $reverse) // compare if the original word is same as the reverse of the same word
echo 'Output: This string is a palindrome';
else
echo 'Output: This is not a palindrome';
?>
» Find string palindrome or not in PHP without using strrev() function
<?php
$mystring = "level"; // set the string
echo "String: " . $mystring;
$myArray = array(); // php array
$myArray = str_split($mystring); //split the array
$len = sizeof($myArray); // get the size of array
$newString = "";
for ($i = $len; $i >= 0; $i--) {
$newString.=$myArray[$i];
}
echo "<br>";
if ($mystring == $newString) {
echo "Output: " . $mystring . " is a palindrome";
} else {
echo "Output: " . $mystring . " is not a palindrome";
}
?>
No comments:
Post a Comment