Jump to content

Can you tell my why this doesn't work?


CyberShot
 Share

Go to solution Solved by Jacques1,

Recommended Posts

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?

 

Link to comment
Share on other sites

  • Solution

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.

  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.