0

I have this code:

echo ( $arr['process_refunds'] == 'storecredit' ) ? 'true' : 'false'

The value in $arr['process_refunds'] is 0 type int(0).

It tried in php -a and it turns out that if we compare any string with == with int(0) it evaluates to true.

Why is that?

Mubashar Abbas
  • 5,536
  • 4
  • 38
  • 49

4 Answers4

5

This is because == is a loosely-typed comparison operator. It is converting your string to a number, therefore it evaluates to true. Try using ===.

Your string is getting converted to a zero because it starts with a letter.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
3

I think it's pretty obvious that the loose comparison is not returning expected values. You can see the comparison table here (2nd table)

http://php.net/manual/en/types.comparisons.php

you can see that this is expected behaviour. This is because php converts the string "php" or "somestr"to a match the number type, making it equal to 0, before making the assessment.

enter image description here

Unless there are other types/conditions you're looking to match with a loose comparison, to get around this, you should use === that will assure you have the matching type.

Daniel
  • 34,125
  • 17
  • 102
  • 150
1

Firstly:

php -r "echo ( $arr['process_refunds'] == 'storecredit' ) ? 'true' : 'false';"

prints:

false

It is obvious because $arr is undefined. But if it has value 0 then

php -r "echo ( 0 == 'storecredit' ) ? 'true' : 'false';"

prints:

true

because both 0 and 'storecredit' are converted to integers.

Value of (int) 'storecredit' is 0 because of it does not contain any number on start of string. For example string '4ss' would be converted to 4.

Daniel
  • 7,684
  • 7
  • 52
  • 76
0

You need no use === because in that way you compare both values are the same type and the same content; example

echo 0 === 'somstr'; // returns false

echo 0 == 'somstr';  //return true