3

I'm confused by something I just ran into in a script I was working on. I had the following:

function getPart($part)
{
    $array = array('a', 'b', 'c');
    if ($part == 'first') $part = 0;
    if ($part == 'last') $part = count($array) - 1;
    if (isset($array[$part])) return $array[$part];
    return false;
}

$position = 0;
echo getPart($position);

So, if I were to try the string "first", I should get "a" as the output. With the string "last" I should get "c" and so on. When I run the script above, with PHP 5.3, I get "c" ...

Confused, I ran a quick test ...

var_dump(0 == 'first');
var_dump(0 == 'last');

Both return TRUE ... WHY??? I am so confused by this behavior!

Nathan Loding
  • 3,185
  • 2
  • 37
  • 43

4 Answers4

6

If you try to compare a string to a number, PHP will try to convert the string to a number. In this case, it fails to do so, since PHP can't convert "first" or "last" into a number, so it simply converts it to zero. This makes the check 0 == 0, which is, of course, true. Use the identity operator, ===, if you want PHP to not attempt to convert anything (so, the two operands must have the same value and be of the same type).

EdoDodo
  • 8,220
  • 3
  • 24
  • 30
  • I am so used to comparing a string "1" and an integer 1 that this didn't cross my mind. One of the down sides to a weakly typed language. – Nathan Loding Jul 12 '11 at 00:00
3

Check out (int) 'first'. That is essentially what PHP is doing to the right hand operand.

PHP will coerce operand types when not using the strict equality comparison operator (===) between two operands of different types.

alex
  • 479,566
  • 201
  • 878
  • 984
1

PHP is weakly typed. What's happening there is it's trying to convert "first" to a number. It fails, and returns zero. It now has two numbers: zero and zero. To make it not try to convert the types, use === rather than ==.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
-1

PHP is a bit strange in that it treats a string in numeric comparison as 0. You can force string comparison by quoting the variables:

function getPart($part)
{
    $array = array('a', 'b', 'c');
    if ("$part" == 'first') $part = 0;
    if ("$part" == 'last') $part = count($array) - 1;
    if (isset($array[$part])) return $array[$part];
    return false;
}
Cfreak
  • 19,191
  • 6
  • 49
  • 60