1

Why does this always return true:

$s = '334rr';
$i = (int)$s;

if ($i == $s) {
    echo true;
} else {
    echo false;
}

If I echo $i it gives the value of 334, which is different from $s which is 334rr.

Mikulas Dite
  • 7,790
  • 9
  • 59
  • 99
sid606
  • 325
  • 1
  • 5
  • 13

5 Answers5

4

From the manual:

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.

So: ($i == $s) is the same as ($i == (int)$s) for the values you've given.

Use === to avoid type-juggling.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

When compare string with integer using ==, string will try to case into integer.

xdazz
  • 158,678
  • 38
  • 247
  • 274
2

Try this

$s = '334rr';
$i = intval($s);
if ($i == $s) {
 echo true;
 } else {
  echo false;
}
Wearybands
  • 2,438
  • 8
  • 34
  • 53
0

Comparing strings to an int is not recommended. You should use the === instead which will verify the same data type as well as the same value.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
0

PHP converts the $s string to an integer when comparing to another integer ($i). It basically does this (well, i don't know what it does internally, but it boils down to this):

if($i == (int) $s)

Which makes the statement true

Ivan Pintar
  • 1,861
  • 1
  • 15
  • 27