2

This is absolute insanity. I was testing a post variable today that should always evaluate to a single character. Example code is...

if($_POST['status'] == '' || $_POST['status'] == 0){ die('oh no!'); }

If I pass a status of P, it was executing the die statement. I then created a PHP file with the following code...

echo 'P1: '.intval($_POST['status']=='').'<br />';
echo 'P2: '.intval($_POST['status']==0).'<br />';
echo 'P3: '.intval('P'==0).'<br />';

Guess what? P2 & P3 both evaluate to TRUE. The intval is there just to show 0 instead of nothing on P1.

Is this a known bug of PHP? Is this just something that is broken on the version I am running? Frankly, I'm at a complete loss as to why it is doing this. It evaluates correctly using triple equals, but not on double. P definitely doesn't equal 0 in my book...

GameCharmer
  • 614
  • 1
  • 7
  • 20

3 Answers3

10

From PHP documentation:

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.

Tchoupi
  • 14,560
  • 5
  • 37
  • 71
  • Waiting 8 more minutes and I'll accept it. Man, that just doesn't seem right, bit it looks like it is. – GameCharmer Jan 23 '13 at 18:42
  • 2
    @GameCharmer: it's the same in most other languages that are type-permissive. php tries to do its best to interpret what you want, but if you insist on doing "giraffe == plasma tv", then it's just GIGO... – Marc B Jan 23 '13 at 18:49
  • 1
    @GameCharmer It's convenient if you try to compare `3 == '3'` for example, which we do very often in PHP. `'P' == 0` is counter-intuitive but follows that very same logic. – Tchoupi Jan 23 '13 at 18:52
1

Read the php manual on comparison's. 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.

If you don't want to have the conversion to happen you need to use triple equals.

$a === $b

TRUE if $a is equal to $b, and they are of the same type

Where $a == $b

TRUE if $a is equal to $b, and they are of the same type.

.

scrappedcola
  • 10,423
  • 1
  • 32
  • 43
1

While comparing string and number by using ==, PHP converts that string to number.

The string 'P' doesn't have any numeric character in it. Therefore, PHP evaluates it to number 0. Finally 0 == 0 happens, which is true.

On the other hand, if you use triple equals (===), that mentioned conversion doesn't happen. PHP expects their types to match as well. Because one of them is string, other is number, it returns false.

tcak
  • 2,142
  • 1
  • 16
  • 23