user3766478
user3766478

Reputation: 691

Brackets and assignment inside of php's IF

Question:

Code 1 and Code 2 has got 1 difference - brackets.

I do not get why 1st causes error but 2nd not.

Code 1:

if
(
    $response = $myObject->response($request)
    && $response2 = $myObject->response($response) // PHP Notice: Undefined variable: response 
)

Code 2:

if
(
    ($response = $myObject->response($request))
    && $response2 = $myObject->response($response) // Everything is OK
)

Upvotes: 0

Views: 210

Answers (6)

axiac
axiac

Reputation: 72226

As several others already said, && has higher priority than = (which is assignment, not comparison) and your code is the same as if ($a = ($b && $c) = $d) (put your own expressions instead of $a .. $d).

This reads: "assign $d to $b && $c then assign it to $a". But $b && $c is an expression, not a variable, you cannot assign $d to it. It's like you say "store $d in 2+2".

Check the operators precedence in PHP manual.

If your intention is to do assignments then write it like if (($a = $b) && ($c = $d)), otherwise use the correct comparison operator if ($a == $b && $c == $d) and you don't need to use parenthesis.

Upvotes: 0

dashtinejad
dashtinejad

Reputation: 6253

The first one is equal to:

if (
    $response = (
        $myObject->response($request) &&
        ($response2 = $myObject->response($response)) // the $response is not defined here
    )
)

The second one is equal to:

if (
    ($response = $myObject->response($request))      // the $response is defined here
    && ($response2 = $myObject->response($response)) // so you can use it  
)

Upvotes: 0

Luzan Baral
Luzan Baral

Reputation: 3698

It because && operator has higher precedence than = operator in PHP. Also apply sense of BODMAS rule as in maths, every operation inside bracket is done first. See table lists the operators in order of precedence for PHP:

Operator Precedence

Upvotes: 1

Stephen
Stephen

Reputation: 18917

As @baldrs mentioned, the && operator (logical and) has higher precedence than the assignment operator. Adding parenthesis forces the evaluation of the assignment before the evaluation of the logical and.

Upvotes: 2

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

By giving the bracket ( ) on the whole statement defines the scope, while in the first check they are 2 independent checks with different scopes.

if you define $response  above the if check, it will work as well.

( ) <-- They broaden the scope of the if check that is why it is visible in the second check.

Upvotes: 1

baldrs
baldrs

Reputation: 2161

&& operator has higher precedence than = operator.

The brackets change the order of the evaluation to what you desire, as expressions in brackets are evaluated first(as they do in math).

Upvotes: 4

Related Questions