3

I want to declare a variable in a if statement and use it in the same statement. Is this simply not possible?

Example of problem (not actual use case though...):

if ($test = array('test'=>5) && $test['test'] === 5) {
    echo 'test';
} else {
    echo 'nope';
}

Error message:

NOTICE Undefined variable: test on line number 6

5
  • 7
    Operator precedence: if (($test = array('test'=>5)) && $test['test'] === 5) { echo 'test'; } else { echo 'nope'; } though I wouldn't consider this good coding practise Commented Nov 2, 2017 at 15:16
  • @MarkBaker Thanks! Why do you not consider this a good coding practise? Commented Nov 2, 2017 at 15:19
  • Why would you ever really need to do this? Just curious on the actual usability of this, I can't think of a scenario where it's useful. Commented Nov 2, 2017 at 15:22
  • 1
    Assigning variables inside if expressions can lead to confusion and errors. Someone else (or even you at a later point in time) can't be sure if it was meant to be an assignment or an invalid comparison. Commented Nov 2, 2017 at 15:23
  • This way I can check whether a record is successfully retrieved AND is the compatible with a previously retrieved record, all in one statement. Otherwise I would have to nest if statements. with each else having to do the exact same thing (404 not found) Commented Nov 3, 2017 at 10:31

1 Answer 1

9

Because of Operator Precedence you will need to group the assignment with ():

if ( ($test = array('test'=>5)) && $test['test'] === 5) {
    echo 'test';
} else {
    echo 'nope';
}

A simple use case might be:

if ( ($parts = parse_url($url)) && $parts['port'] == 8080) {
    // do stuff
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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