Reputation: 8200
I would like to add two integers and concatenate their result to a string, that is:
Add 1 to $i
, and concatenate that result to the string 'icon'
. I thought the following syntax would work:
$x = 'icon'.$i+1;
However it doesn't do what I want - it keeps returning the value 'icon1'
, disregarding the value of $i
.
What's the right way to do what I want?
Upvotes: 2
Views: 46
Reputation: 32800
try this :
$temp = $i+1;
$x = 'icon'.$temp;
You are getting wrong answer because of "Operator Precedence",
Ref this link : http://php.net/manual/en/language.operators.precedence.php
Here see the line : left + - . arithmetic and string
.
has more Precedence than +
, So your expression will be like : $x = ('icon'.$i)+1;
To solve it either use the method i mentioned above or hsz answer
ie : $x = 'icon'.($i+1);
Upvotes: 1
Reputation: 16304
Operator Precedence explains why this is happening.
You can use brackets:
$x = 'icon'.($i+1);
This should do the job.
My test:
$i = 18;
$x = 'icon'.($i+1);
var_dump($x);
--> string(6) "icon19"
Upvotes: 1
Reputation: 152284
Try with:
$i = 0; // init $i
$x = 'icon'.($i+1);
If you want to regularly increment $i
variable:
$x = 'icon'.(++$i);
Upvotes: 2