Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP seems to be evaluating an if statement backwards [duplicate]

So I have a PHP statement of the following type:

if ($x=function($y) || $z == 50) {

What I see happening is that if $z is 50, $x doesn't get set because the function is never called. Is that really possible? I can (and did) fix this easily, but I guess I am confused that that's what is happening and want to make sure I don't make mistakes like this going forward I tried to find out how OR expressions like this are evaluated. Is there a place I can look to see how php gets "compiled"?

like image 788
user3656957 Avatar asked May 20 '14 14:05

user3656957


2 Answers

You have operator precedence issue. Check this http://www.php.net/manual/en/language.operators.precedence.php

Because || has higher precedence than = Your expression really looks like this

if ( 
    $x = ( 
        function($y) || ( $z == 50 ) 
    ) 
) 

Instead of (what I think was your intention)

if ( 
    ($x = function($y)) || ($z == 50) 
)
like image 160
mleko Avatar answered Nov 14 '22 12:11

mleko


|| has higher precedence than =, which means your expression becomes:

$x = (foo($y) || ($z == 50));

This means that $x will always be either true or false. Nothing else.

Try:

if( ($x = foo($y)) || ($z == 50))

Or, more readable:

$x = foo($y);
if( $x || $z == 50)
like image 38
Niet the Dark Absol Avatar answered Nov 14 '22 13:11

Niet the Dark Absol