A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam, racecar, 11, 22, 131, 121, etc.
Let’s find palindrome using PHP in-built function
<?php
$n = 'madam'; // User input either string or number. Ex: 131, 121, level
if($n == strrev($n)){
echo "This is palindrome.";
}
else{
echo "Not a palindrome.";
}
Output :
This is palindrome.
Explanation :
Here i’m using “strrev” PHP in-built function which reverse the given input string or number.
Now, let’s find palindrome without using PHP in-built function
<?php
$mystring = 'madam'; // set the string
echo 'String: <b>' . $mystring . '</b>';
$myArray = array(); // initialize an array
$myArray = str_split($mystring); //split into array
$len = sizeof($myArray); // get the size of array
$newString = '';
for ( $i = $len-1; $i >= 0; $i-- ) {
$newString .= $myArray[$i];
}
if ( $mystring == $newString ) {
echo ' is a palindrome';
} else {
echo ' is not a palindrome';
}
Output :
String madam is a palindrome