note 124745 added to language.operators.precedence
| From: | noone@php.net | Date: | Sun, 23 Feb 2020 14:46:37 +0000 |
| Subject: | note 124745 added to language.operators.precedence | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214208@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 45.112.84.4
Probable Submitter: 103.51.167.36 (proxied: 86.58.31.33)
----
Manual Page -- http://php.net/manual/en/language.operators.precedence.php
Edit -- https://master.php.net/note/edit/124745
Del: integrated -- https://master.php.net/note/delete/124745/integrated
Del: useless -- https://master.php.net/note/delete/124745/useless
Del: bad code -- https://master.php.net/note/delete/124745/bad+code
Del: spam -- https://master.php.net/note/delete/124745/spam
Del: non-english -- https://master.php.net/note/delete/124745/non-english
Del: in docs -- https://master.php.net/note/delete/124745/in+docs
Del: other reasons-- https://master.php.net/note/delete/124745
Reject -- https://master.php.net/note/reject/124745
Search -- https://master.php.net/manage/user-notes.php