1

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.

2
  • What you want to use is the equality operator, ===, which will also ensure that the types being compared are the same. Thus, if $code is not 'item_low_stock' or not a string, the comparison works as expected. Commented Dec 4, 2012 at 3:04
  • you can check this too bugs.php.net/bug.php?id=44999 Commented Dec 4, 2012 at 3:07

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Worth mentioning the equality operator, so she gets the results she's expecting.
2

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.

1 Comment

Wow, amazing.. insane! How have I never come across this in all my years of php developing? Thank you! I guess the change in my app was with a library that hadn't been passing the value of 0 in the $code variable before, prior, the codes had all been strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.