note 31401 deleted from language.expressions by victor

From: Date: Sat, 27 Mar 2004 21:57:30 +0000
Subject: note 31401 deleted from language.expressions by victor
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-67265@lists.php.net to get a copy of this message
Note Submitter: cmartin@orlando.fl ---- 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. :)

« previous php.notes (#67265) next »