CyberShot Posted September 9, 2017 Share Posted September 9, 2017 I had a simple array I was playing with. I wanted to number the output so that it would look like this 1. item one 2. item two 3. item three 4. item four and so on. so made a for loop that output my array just fine and tried doing this inside the for loop $counter = 0; // this is outside the loop //inside echo $counter += 1 . '. ' . $myArray[$i] . '<br />'; what that gave me was 1234 instead of 1. item one 2. item two 3. item three 4. item four however, when I separated it like so echo $counter += 1; echo '. ' . $myArray[$i] . '<br />'; it works just fine. Why is that? Quote Link to comment https://forums.phpfreaks.com/topic/304916-can-you-tell-my-why-this-doesnt-work/ Share on other sites More sharing options...
Solution Jacques1 Posted September 9, 2017 Solution Share Posted September 9, 2017 Because of operator precedence. Concatenation binds stronger than assignments, so PHP first builds the string 1 . '. ' . $myArray[$i] . '<br />'; and then "adds" that string to the counter, which discards everything but the leading 1. Of course the real answer is: Don't do this. Precedence is tricky enough (parentheses can help here), but when the expressions also have side effects, even a seemingly simple piece of code can lead to all kinds of bugs. Don't try to save lines of code. 1 Quote Link to comment https://forums.phpfreaks.com/topic/304916-can-you-tell-my-why-this-doesnt-work/#findComment-1551006 Share on other sites More sharing options...
CyberShot Posted September 9, 2017 Author Share Posted September 9, 2017 Thank you. Quote Link to comment https://forums.phpfreaks.com/topic/304916-can-you-tell-my-why-this-doesnt-work/#findComment-1551007 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.