note 124745 deleted from language.operators.precedence by cmb
| From: | cmb@php.net | Date: | Mon, 04 Apr 2022 20:02:52 +0000 |
| Subject: | note 124745 deleted from language.operators.precedence by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218128@lists.php.net to get a copy of this message | ||
Note Submitter: noone
----
Something that threw me of guard and I hadn't found it mentioned anywhere is if you're
looking to asign a value in an if statement condition and use the same value in the said condition
and compare it to a different value note the precedence of operators.
if($a=5&&$a==5){
echo '5';
} else {
echo 'not 5';
}
//echos not 5
You'll get a Notice: Undefined variable: a;
This happens because the expression is treated as
($a=5&&($a==5))
In this case $a was undefined.
Use parentheses to enforce the desired outcome or and instead of &&.
if(($a=5)&&$a==5){ // or $a=5 and $a==5
echo '5';
} else {
echo 'not 5';
}
//echos 5
We get no notice!
A use case for this can be a three part condition that first checks if a value is valid, second
assigns a new variable based on the first value and then checks if the result is valid.
$ID=100;
if ($ID&&($data=get_table_row_for_ID($ID))&&$data->is_valid()) { //NOTE: assigned
$data
// do something with the data
}
If assigning variables in an if condition I recommend adding a comment at the end of the line that
such an action took place.