|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2017-03-29 08:15 UTC] pierstoval at gmail dot com
Description: ------------ --- From manual page: http://www.php.net/language.operators.precedence --- There's an inconsistency in Example #2 on the "Language Operators Precedence" page. The example states that the script "may print either 2 or 3", but actually, it will *always* print "3", and for the second script, the array will *always* be equal "[2 => 1]". This might confuse people about the real role of precedence operators. You can check on 3v4l here: https://3v4l.org/EUknn Test script: --------------- // First script $a = 1; echo $a + $a++; echo "\n"; // Second script $i = 1; $array[$i] = $i++; var_export($array); Patchesfix-precedence-doc-inconsistency (last revision 2017-03-29 08:20 UTC by pierstoval at gmail dot com)Pull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 07 19:00:01 2026 UTC |
You're already confused about what precedence means. Precedence (and associativity) is about grouping operands and says that (eg) $a+$b*$c will be interpreted as $a+($b*$c). It does not say that $a+$b*$c will be *executed* using $b first, $c second, and $a third - or any other way. > echo $a + $a++; PHP does not guarantee when the $a and $a++ are evaluated. It could be that the $a comes first (=1) and the $a++ second (=1 and $a=2) resulting in 1+1=2, or it could be that $a++ comes first (=1 and $a=2) and $a second (=2) resulting in 1+2=3. > $array[$i] = $i++; Same situation. PHP does not guarantee when the $i and $i++ are evaluated. It could be that the $i comes first (=1) and the $i++ second (=1 and $i=2) resulting in 1=>1, or it could be that $i++ comes first (=1 and $i=2) and $i second (=2) resulting in 2=>1. Consider: function f() { echo "f"; return 1; } function g() { echo "g"; return 2; } function h() { echo "h"; return 3; } echo f() + g() * h(); Precedence states it will be grouped as f+(g*h) and thus the result will be 1+(2*3)=7. But do you know how it will be executed? Are you sure? Take a look: https://3v4l.org/LVr4o Your homework is to learn about operator precedence vs. order of evaluation, and optionally what sequence points are. It's mostly about C but a lot applies to PHP too.