0

Just curious why this would trigger a warning.
Note: query string param "test" is not included in the URL

//Notice: Undefined index: test 
if($_GET['test'] === 'somestring' && !empty($_GET['test'])) {
}

//Valid - No Warning.  Why is this Valid? Param 'test' was never given
if(!empty($_GET['test']) && $_GET['test'] === 'somestring') {
}

Is this because PHP evaluates from LEFT to RIGHT? And not the whole condition?

7
  • 2
    Most languages will "short-circuit" logic statements to avoid unnecessary computation. && statements will stop at the first false and || statements will stop at the first true. In PHP you can use this to write otherwise-unsafe statements, like your second example. Commented Jun 11, 2018 at 21:07
  • @Sammitch "most" ? Interesting. Is there any language which evaluates all results irrespective of earlier results? Commented Jun 11, 2018 at 21:08
  • @mehulmpt not specifically, no. Commented Jun 11, 2018 at 21:11
  • 2
    Yes VBA tries all statements before it continues. @mehulmpt Commented Jun 11, 2018 at 21:14
  • 1
    Neither are better or worse practice, and they are equivalent statements. Commented Jun 11, 2018 at 22:52

3 Answers 3

2
if(!empty($_GET['test']) && $_GET['test'] === 'somestring') {

Because you're using &&, if any condition is false, further conditions are not checked. Conditions are checked in the order they're written. Since here, first condition !empty($_GET['test']) is false, the next one does not evaluate hence no warning.

Sign up to request clarification or add additional context in comments.

Comments

1

In the first example:

//Notice: Undefined index: test 
    if($_GET['test'] === 'somestring' && !empty($_GET['test'])) {
}

you are trying to access the value of the variable first, before checking if it exists, which is what the second example is basically doing. After checking that it does not exist, it exits the conditional without testing the second part.

Comments

0

Simply put, it comes down to operator precedence.
The documentation shows that && is evaluated left-to-right, which means the left part of the clause is evaluated first. In your case, that clause results in a warning. If you reversed your clause order, the empty() check would return false, then the logic would short circuit and stop evaluating.

1 Comment

This isn't about precedence, it's about short-circuiting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.