jessica
jessica

Reputation: 3131

PHP Sanity Check, conditional / comparison

Can someone, for the love of all things natural, please explain why this is happening?

$code = 0;
echo $code == 'item_low_stock' ? 'equal' : 'not equal';

// RESULT: "equal"  

???

A line of code in my app just suddenly stopped working properly, I haven't edited anything around it, changed my php version, anything. When the $code variable contains 0, it is passing as true when I compare it to the string 'item_low_stock'.

I can post the original block of code, but I boiled it down to this comparison and this is what I found.

Halp.

EDIT: PHP version is 5.3.10.

Upvotes: 1

Views: 392

Answers (2)

Sampson
Sampson

Reputation: 268324

The documentation makes it clear that the two values on either side of == are tested after type juggling. When cast to an integer, your string becomes 0. Try the following:

echo (int) 'item_low_stock'; // 0

Run it: http://codepad.org/z7LIEumk

If you don't want to engage in type juggling, use === or !== instead. This tests whether the two values are * identical*, meaning same value and type.

Upvotes: 4

zerkms
zerkms

Reputation: 254886

When one of operands is a number - then php casts another one to a number as well.

So item_low_stock string casted to number is 0, thus it equals to 0, thus it's true

http://php.net/manual/en/language.operators.comparison.php

If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

Upvotes: 2

Related Questions