Search code examples
phppalindrome

How to make PHP see my variable as a number?


So while i was doing my homework i stuck on one point.

The excercise is based on making a function which checks if $word is a palindrome, from my tests $L works and is moving forward to right side of the word ($L starts from left, $R from right) but $R is not working at all, if $R is swapped by a number - it works. If $R is printed, it shows right number - 5.

$word = "madam";

function palindrome($s)
{
    $i = intval(strlen($s) / 2);    
    $L = 0;                 
    $R = strlen($s);        
    $pal = true;            

    for($i; $i>0; $i--)
    {
        if($s[$L] != $s[$R]) $pal=false;
        $L++; 
        $R--;
    }

    if($pal==true)
        print("palindrome");
    else
        print("not a palindrome");
}

palindrome($word);

I expect to make $R an value, i suspect that PHP sees it as a string, not an integer, but i don't know why. I would be very happy if someone helped me with that.


Solution

  • If you consider string as char table, index starts at 0, but strlen count from 1 so if you have 'madam' then strlen() returns 5 but last chatacter is on $s[4], simply use:

    $R = strlen($s)-1;