Ernest Marcinko
Ernest Marcinko

Reputation: 405

Evaluation and assignment in if statement

I'm wondering, will this work with any major PHP versions?

if ($foo != $bar && '' != $str = some_function($some_variable))
    echo $str;

The some_function($some_variable) returns a string, which is assigned to the $str variable and then checked if is an empty string. The $str variable is used later of course.

Will be the output of the some_function assigned to the $str variable in every major PHP version (>5)? I couldn't find any information on this. Thanks.

I'm currently running 5.4 and it's working.

Edit: To avoid further confusion, the $foo != $bar precedes the other expression because the $str variable is only used inside the if statement. Sorry, I forgot to clarify that.

Upvotes: 0

Views: 133

Answers (3)

Thijs Riezebeek
Thijs Riezebeek

Reputation: 1812

I would not see why this would not work in any PHP version (> 5). Tested here: http://sandbox.onlinephpfunctions.com/code/a295189c50c191bbd0241d4e8ea4e3081cdb40ae

Worked with all the versions from 4.4.9 and up.

Note: Because you are using the && operator, the code after the && will not be run if $foo != $bar already returns false, since the second expression cannot change the outcome of the && operator, therefore it will simply ignore it.

If the assignment is intented to always take place, then change the order of the expressions.

if ('' != $str = some_function($some_variable) && $foo != $bar)
    echo $str;

Upvotes: 2

lightup
lightup

Reputation: 674

Why don't you make it clear and not confusing by using brackets and curly braces. Example:

if (($foo != $bar) && '' != ($str = some_function($some_variable)) ) {
       echo $str;
}

Upvotes: 1

Rizier123
Rizier123

Reputation: 59681

Yes it does work, but to get it working like you want you have to put brackets around the assignment, because the comparison has a higher precedence then the assignment! (operator precedence)

Also if $foo != $bar is false the $str would never been initialize so also change the order, so that it get's assigned ever time.

So use this:

if ('' !== ($str = some_function($some_variable)) && $foo != $bar)
     //^^^ ^ See here                   And here^
     //| '!==' to also check the type

Upvotes: 4

Related Questions