1

So I have this function and I'm trying to understand how this is true and how it comes out false if I use === instead of == .

function is_equal($value1, $value2) {
    $output = "{$value1} == {$value2}: ";
    if ($value1 == $value2) {
        $output = $output . "true<br />";
    } else {
        $output = $output . "false<br />";
    }

    return $output;

}

echo is_equal("123", "   123");
echo is_equal("123", "+0123");

?>

this code above comes out true because I'm testing for == how is that? and also if I use === it's false

Shire
  • 39
  • 2
  • 9
  • Because there's a difference between those two operators $a == $b Equal TRUE if $a is equal to $b after type juggling. $a === $b Identical TRUE if $a is equal to $b, and they are of the same type. – user3350731 Jul 30 '14 at 20:54
  • To be fair to @Shire, this would not be your expectation, even if you were familiar with type juggling - the inputs are of the same type, so you would expect them to be compared as strings. This is one of the surprises of PHP: `'123' == ' 123'`. – Fenton Jul 30 '14 at 20:57
  • so is just a PHP quirk?. Wow I like PHP but this can get annoying down the road. – Shire Jul 30 '14 at 20:58
  • Also just discovered that the integer zero, 0 == 'most strings'. Read up: https://josephscott.org/archives/2012/03/why-php-strings-equal-zero. This definitely caused a lot of head scratching (or head banging). – earth2jason Apr 24 '15 at 01:37

3 Answers3

1

When you compare equality using ==, PHP will juggle the types. I suspect your types are being juggled resulting in a numeric comparison.

When you compare equality using === the type is compared first, followed by the values.

Fenton
  • 241,084
  • 71
  • 387
  • 401
0

Yes, this is right. === will compare the value and the typeinstead of == that is comparing if values are identical.

You can also try this one :

echo is_equal("123", 123);
Kevin Labécot
  • 2,005
  • 13
  • 25
0

=== tests whether the two variables are identical (same value, same type). == tests for equality and does type juggling for you.

Read up over here.

Oliver
  • 3,981
  • 2
  • 21
  • 35