PHP ||/OR In Function

Discussion in 'PHP' started by MMJ, Dec 5, 2007.

  1. #1
    Surprisingly enough I don't get a parse error from this:

    if (is_bool('a' || 10))
    	echo 'Is boolean';
    PHP:
    This echos "Is boolean". Whats happening here?

    PHP 5.2.3
     
    MMJ, Dec 5, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    Both values will be casted to boolean, and both would be true.

    Let's rewrite it so you understand it better.
    
    $foo = 'a'; // 'a' casted to boolean is true. (bool)'a' === true
    $bar = 10; // 10 casted to boolean is true too. (bool)10 === true
    
    // When you're doing this, PHP will cast both values to boolean and operate with the given operator.
    $bool = 'a' || 10; // OR: If 'a' or 10 is True - Return true
    
    // $bool is now boolean True, so:
    if (is_bool($bool))
        echo 'Is boolean';
    
    // ... is true.. and the text is outputted.
    
    PHP:

    This syntax can be useful for thing like this:
    
    if ($foo == 'a' OR $bar == 10)
    {
        $bool = true;
    }
    else
    {
        $bool = false;
    }
    
    // The above can be simplified to:
    $bool = $foo == 'a' OR $bar == 10;
    
    // $bool is now boolean true
    
    PHP:
     
    nico_swd, Dec 5, 2007 IP
    MMJ likes this.
  3. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Wow, that helps. I didn't really think of it that way.

    So PHP is converting the parameter before the function looks at it. Thats what was confusing me.

    This is a bit more apparent: is_bool(('a' || 10))

    Thanks!
     
    MMJ, Dec 5, 2007 IP