0
<?php
    var_dump($isHoster); // prints int(0)

    if ($isHoster == 'all')
        $conditionsHoster = '0, 1';
    else
        $conditionsHoster = intval($isHoster);

    var_dump($conditionsHoster); // prints string(4) "0, 1"
?>

What is going on?? Who can explain that? This never happened to me...

jotik
  • 17,044
  • 13
  • 58
  • 123
user1711384
  • 343
  • 1
  • 7
  • 24
  • 1
    Relevant manual documentation: http://php.net/manual/en/language.types.string.php#language.types.string.conversion – Amal Murali Mar 25 '14 at 15:13
  • Why? "all" can never be the same as 0. – user1711384 Mar 25 '14 at 15:13
  • 1
    It doesn't make any sense, but that's how PHP does it. It's safer comparing things of the same type or using `===` instead. – Dissident Rage Mar 25 '14 at 15:14
  • 1
    That's how PHP rolls. Please take a look at this question and its answers: [Why does PHP consider 0 to be equal to a string?](http://stackoverflow.com/questions/6843030/why-does-php-consider-0-to-be-equal-to-a-string) - that might give you a better idea. – Amal Murali Mar 25 '14 at 15:15
  • 1
    okay thanks guys...this destroys my worldview – user1711384 Mar 25 '14 at 15:17
  • 1
    Obligatory: http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/ – d33tah Mar 25 '14 at 15:17
  • 1
    'all' is not the `same` as 0 but it does evaluate to 0 when it is type-cast. `===` checks for `sameness` (type and value). – AbraCadaver Mar 25 '14 at 15:30

2 Answers2

6

0 == 'all' is true in php because php tries to convert 'all' to int and (int) 'all' is 0; you should write

if ($isHoster === 'all')
vee
  • 38,255
  • 7
  • 74
  • 78
alez007
  • 276
  • 1
  • 6
1
    var_dump($isHoster); // prints int(0)

    if ($isHoster === 'all')
        $conditionsHoster = '0, 1';
    else
        $conditionsHoster = intval($isHoster);

    var_dump($conditionsHoster);

Its because you are comparing Int with String. Before comparing convert $isHoster to string like $isHoster = (string) $isHoster; or user === to compare.

shivanshu patel
  • 782
  • 10
  • 19