note 31401 added to language.expressions

From: Date: Sun, 20 Apr 2003 16:34:54 +0000
Subject: note 31401 added to language.expressions
Groups: php.notes 
Request: Send a blank email to php-notes+get-46851@lists.php.net to get a copy of this message
Got into trouble here when not enclosing my multiple expressions in parenthesis: if ($res = mysql_query($query) && $row = mysql_fetch_assoc($res)) { echo "Got DB Row!: "; print_r($row); } Results in a PHP warning: PHP Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in test.php on line 10 Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in test.php on line 10 By adding parenthesis around the assignment expressions... if (($res = mysql_query($query)) && ($row = mysql_fetch_assoc($res))) { echo "Got DB Row!: "; print_r($row); } ...results in the desired output: Got DB Row!: Array ( [id] => 0 [name] => "Foo!" ) A closer look at what happens when the right value of an assignment is false (when used as a test expression): $a = 0; if ($b = $a && $c = $b) { echo "Test true: "; } echo "a:$a b:$b c:$c"; ...yields $b and $c as unset: a:0 b: c: ...while parenthesis modify $b's result: $a = 0; if (($b = $a) && ($c = $b)) { echo "Test true: "; } echo "a:$a b:$b c:$c"; ...as $b being set and $c remaining unset (desired): a:0 b:0 c: One may want to always enclose their singular expressions within parenthesis to avoid this feature/problem. :) -- http://www.php.net/manual/en/language.expressions.php http://master.php.net/manage/user-notes.php?action=edit+31401 http://master.php.net/manage/user-notes.php?action=delete+31401 http://master.php.net/manage/user-notes.php?action=reject+31401

« previous php.notes (#46851) next »