note 75641 added to language.operators

From: Date: Sat, 09 Jun 2007 22:17:29 +0000
Subject: note 75641 added to language.operators
Groups: php.notes 
Request: Send a blank email to php-notes+get-127340@lists.php.net to get a copy of this message
In response to mathiasrav at gmail dot com: The reason for that behavior is the parentheses. From the description: "Parentheses may be used to force precedence, if necessary. For instance: (1 + 5) * 3 evaluates to 18." So the order of operations says that even though the equality operator has higher precedence, the parentheses in your statement force the assignment operator to a higher precedence than the equality operator. That said, it still doesn't work the way you expect it to. Neither way works, for these reasons: <?php if ( $a != ($a = $b) ) ?> Order of operations says to do the parentheses first. So you end up with: <?php $a = $b; if ( $a != $a ) ?> Which is obviously going to be false. Without the parentheses: <?php if ( $a != $a = $b ) ?> Order of operations says to do the inequality first, then the assignment, so you have: <?php if ( $a != $a ); $a = $b; ?> Which again is not what you expected, and again will always be false. But because you are only working with values of 0 and 1, you can make use of the XOR operator: <?php if ( $a ^= $b ) ?> This will only be true if 1) $a is 0 and $b is 1, or 2) $a is 1 and $b is 0. That is precisely what you wanted, and it even does the assignment the way you expected it to. <?php foreach ($ourstring as $c) { if ($bold ^= $c['bold']) $resstring .= bold; if ($underline ^= $c['underline']) $resstring .= underline; $resstring .= $c[0]; } ?> That code now works and produces the output you expected. ---- Server IP: 69.39.81.135 Probable Submitter: 67.10.104.143 ---- Manual Page -- http://www.php.net/manual/en/language.operators.php Edit -- https://master.php.net/note/edit/75641 Del: integrated -- https://master.php.net/note/delete/75641/integrated Del: useless -- https://master.php.net/note/delete/75641/useless Del: bad code -- https://master.php.net/note/delete/75641/bad+code Del: spam -- https://master.php.net/note/delete/75641/spam Del: non-english -- https://master.php.net/note/delete/75641/non-english Del: in docs -- https://master.php.net/note/delete/75641/in+docs Del: other reasons-- https://master.php.net/note/delete/75641 Reject -- https://master.php.net/note/reject/75641 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#127340) next »