Skip to main content
Better version based on comments.
Source Link

Others have pointed out a fix you could make to your implementation. But there is a way to write this which is much simpler. That takes advantage of a simplified definition of palindrome: "a word which reads the same forwards and backwards".

Now I haven't done PHP in years, and don't have a test environment, so this might have issues, but the basic idea should be clear.

public static function isPalindrome($word)
{
    return $word == strrev($word);
}

Update

Based on suggestions in the comments, this would be nicer:

function isPalindrome($word) {
    $word = preg_replace('/[^a-zA-Z]/', '', $word);
    $word = strtolower($word);
    return $word == strrev($word);
}

That will now correctly identify "Level" (ignoring capitalization) and "Madam, I'm Adam." (ignoring spaces and punctuation.)

Others have pointed out a fix you could make to your implementation. But there is a way to write this which is much simpler. That takes advantage of a simplified definition of palindrome: "a word which reads the same forwards and backwards".

Now I haven't done PHP in years, and don't have a test environment, so this might have issues, but the basic idea should be clear.

public static function isPalindrome($word)
{
    return $word == strrev($word);
}

Others have pointed out a fix you could make to your implementation. But there is a way to write this which is much simpler. That takes advantage of a simplified definition of palindrome: "a word which reads the same forwards and backwards".

Now I haven't done PHP in years, and don't have a test environment, so this might have issues, but the basic idea should be clear.

public static function isPalindrome($word)
{
    return $word == strrev($word);
}

Update

Based on suggestions in the comments, this would be nicer:

function isPalindrome($word) {
    $word = preg_replace('/[^a-zA-Z]/', '', $word);
    $word = strtolower($word);
    return $word == strrev($word);
}

That will now correctly identify "Level" (ignoring capitalization) and "Madam, I'm Adam." (ignoring spaces and punctuation.)

Source Link

Others have pointed out a fix you could make to your implementation. But there is a way to write this which is much simpler. That takes advantage of a simplified definition of palindrome: "a word which reads the same forwards and backwards".

Now I haven't done PHP in years, and don't have a test environment, so this might have issues, but the basic idea should be clear.

public static function isPalindrome($word)
{
    return $word == strrev($word);
}