Jump to content

Can you tell my why this doesn't work?


CyberShot

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

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.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.