Reputation: 3477
Here is the sample:
if(($test = array('key'=>true)) && $test['key']){
// works
}
if($test = array('key'=>true) && $test['key']){
// does not work
}
Why is the parenthesis required? My understanding is that it computes the first conditional then the second no matter what.
And is it "safe" to do an assignment like this?
Upvotes: 2
Views: 121
Reputation: 8003
In PHP, the assignment operator =
has lower precedence that most other operators. (For more information, see the documentation). Furthermore, the result of an expression using the assignment operator is the value of the assignment. With this in mind, consider the expressions you posted:
First example:
($test = array('key'=>true)) && $test['key']
The first part of this expression, ($test = array('key'=>true))
evaluates to array('key'=>true)
(by the rule above), and the second part evaluates to true
since the key was just set. Thus the whole expression evaluates to true
.
Second example:
$test = array('key'=>true) && $test['key']
By the rules of operator precedence, $test
is going to get assigned the value of the expression array('key'=>true) && $test['key']
. The first half of this is true, but $test['key']
hasn't been set yet, so true && false
is false, so $test
takes the value false
, which is also the result of the if condition.
Upvotes: 0
Reputation: 42046
It is safe to use, but in this case the parenthesis are required for disambiguation. The operator precedence rules of PHP mean that the second line will be executed as:
if ($test = (array('key' => true) && $test['key'])) { .. }
So test will not be an array but a bool.
The practice of doing assignment in if statements itself is not really encouraging readability though, so you probably want to avoid doing this too much.
Upvotes: 0
Reputation: 54445
It's because it's forcing the interpreter to perform the assignment before it attempts to evaluate any of conditions within the if.
Without the parenthesis, you're simply assigning the results of array('key'=>true) && $test['key']
to $test.
Upvotes: 0
Reputation:
i don't think the parens are required in PHP. they are in JS.
depends what you mean by "safe". it works. but some would argue that this is bad style and makes for less understandable and less maintainable code. otoh, K&R positively recommended it. it doesn't worry me and sometimes makes for tidier code.
Upvotes: 0
Reputation: 218960
It's a matter of operator precedence in the language. In your second statement, you're essentially writing this to be evaluated:
$test = array('key'=>true) && $test['key'];
Just about any language is going to take that to mean this:
$test = (array('key'=>true) && $test['key']);
It's assigning to $test
the value of the evaluation of the logical &&
between the two other values. So $test
will be either true
or false
when evaluated.
Upvotes: 8