list(), if and short-circuit evaluation
An answer to this question on Stack Overflow.
Question
I have the following code snipplet:
$active_from = '31-12-2009';
if(list($day, $month, $year) = explode('-', $active_from)
&& !checkdate($month, $day, $year)) {
echo 'test';
}
Why do I get an undefined variable error?
list($day, $month, $year) = explode('-', $active_from) returns true, so list() is evaluated, isn't it? I think, the variables should be defined? What do I oversee?
This does in my opinion the same and throws no error:
$active_from = '31-12-2009';
list($day, $month, $year) = explode('-', $active_from);
if(checkdate($month, $day, $year)) {
echo 'test';
}
This raises no error:
if((list($day, $month, $year) = explode('-', $active_from)) && checkdate($month, $day, $year)) {
But I really don't understand why :-)
Thanks for explanation
Answer
This is an issue of operator precedence, in your case, the && evaluates before the =, leading to the errors you describe.
You can resolve this problem by placing the assignment statement inside of a parentheses.
Explicitly, your code should read
if( (list($day, $month, $year) = explode('-', $active_from))
&& !checkdate($month, $day, $year)) {
Note that I have changed it from if( $a=$b && $c ) to if( ($a=$b) && $c ). The parentheses force the assignment operator (=) to evaluate before the conjunction (&&), which is what you want.