Soyab Badi
1 min readJun 7, 2021

--

Verify given string is palindrome or not with rearrange form?

Many interviewer ask question “How would you verify given string is palindrome or not in the PHP?”

It is very simple!

<?phpfunction checkPalindrome($s): bool
{
$r = strrev($s); // revers the string
return ($s == $r);
}
$input = 'madam';
$output = checkPalindrome($input);
echo ($output) ? 'Given string is palindrome' : 'Given string is not palindrome';

What if interviewer ask “Check given string is palindrome or not after rearrangement of string character?”

Need to think out of the box & Rub the brain!

<?phpfunction checkPalindrome($s): bool
{
$break = str_split($s); // Convert string to array
$countChar = array_count_values($break); // Count of character
$oddChar = [];
foreach ($countChar as $k => $v) {
$check = $v % 2; // Check odd or even
if ($check) {
$oddChar[] = $k;
}
}
// Odd character count more than one treat as non palindrome string
if(count($oddChar) > 1){
return false;
}
return true;
}

$output = checkPalindrome('madam');

echo ($output) ? 'Given string is palindrome' : 'Given string is not palindrome';

Logic

“Given string each character count should not odd number more than one time otherwise given string never be palindrome string.”

--

--

Soyab Badi
0 Followers

Sr. Software Engineer / Sr. Web Developer / Sr. PHP Developer / Laravel Developer / Codeignitor / PHP Trainer / Laravel Developer