<?php
function is_palindrome($str) {
$len = strlen($str);
if ($len < 2) {
// strings of 0 or 1 characters are palindromes
return true;
}
elseif ($str[0] != $str[$len-1]) {
// first character doesn't match last character, so not a palindrome
return false;
}
else {
// first character is equal to last character,
// so see if the rest of the string is a palindrome
return is_palindrome(substr($str, 1, $len - 2));
}
}
foreach (['rotor', 'a', 'deed', 'hello', 'xyyz'] as $str) {
echo "\"$str\" is" . (is_palindrome($str) ? "" : " not") . " a palindrome\n";
}
function is_palindrome_broken($str) {
$len = strlen($str);
if ($len < 2) {
// strings of 0 or 1 characters are palindromes
return true;
}
elseif ($str[0] != $str[$len-1]) {
// first character doesn't match last character, so not a palindrome
return false;
}
else {
// first character is equal to last character,
// so see if the rest of the string is a palindrome
is_palindrome_broken(substr($str, 1, $len - 2));
}
}
foreach (['rotor', 'a', 'deed', 'hello', 'xyyz'] as $str) {
echo "\"$str\" is" . (is_palindrome_broken($str) ? "" : " not") . " a palindrome\n";
}