1

I have put together this Palindrome function in PHP

<?php
// example code

function isPalindrome($str){
    // eliminate special chars
    $str = preg_replace('/[^a-z0-9]+/i', '', $str);

    // all to lowercase
    $str = strtolower($str);

    // reverse string
    $strArr = str_split($str);
    $strArr = array_reverse($strArr);
    $reversed_str = join('',$strArr);

    //Test
    //echo $str . ' | ' . $reversed_str;

    // compare
    return $str === $reversed_str;

}

echo isPalindrome("A nut for a jar of tuna"); // returns 1

The problem: if the supplied string is a palindrome, the function returns 1, otherwise it returns nothing.

echo isPalindrome("A nut for a jar of fish"); // returns no output (in https://www.tehplayground.com)

I want it to return either true or false. Where is my mistake?

deceze
  • 510,633
  • 85
  • 743
  • 889
Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252

1 Answers1

2

Your function doesn't return 1 or nothing, it is the echo that decides to render the result that way.

Try

var_dump(isPalindrome("A nut for a jar of tuna"));

if (isPalindrome("A nut for a jar of tuna") === true) {
     echo 'true';
} else {
     echo 'false';
}

to get some more debug friendly output

Loupax
  • 4,728
  • 6
  • 41
  • 68
  • 1
    This is a form of over-engineering, I wish it worked as I had expected it to (it works in JavaScript). Thanks for the answer. – Razvan Zamfir Oct 07 '19 at 12:12