How do i break an in-string variable in php?

173 Views Asked by At

This should be simple to answer. When I have a variable, say $id, and in a string, I want it between two underlines. Something like this:

$id = 1;
$myString = "row_$id_info";

Now, php will see "row_" and the variable $id_info - And that's not what I want.

So my question is plain: How do i break an in-string variable in php?

Thanks for all replies

8

There are 8 best solutions below

1
On BEST ANSWER

In such cases enclose the variable in {}

$id = 1;
$myString = "row_{$id}_info"; // $myString is row_1_info
4
On

You mean this:

$id = 1;
$myString = "row_" . $id . "_info";

Or

$myString = "row_{$id}_info";

See: PHP String Concatenation

1
On

$myString = "row_".$id."_info";

1
On

Actually that should do the trick since quotes are parsed for varaibles and you actually supplied the name. However concatenating is what you're asking for.

$id = 1;
$myString = 'row_'.$id.'_info';
0
On
$id = 1;
$myString = "row_{$id}_info";
0
On

Use curly braces:

$myString = "row_{$id}_info";
0
On
$myString = sprintf("row_%d_info", $id);

Using this $id is also checked against being numeric.

7
On
$myString = "row_{$id}_info";

or, "better" (more readable) and faster:

$myString = "row_".$id."_info";

EDIT:

plase take a look at this link - putting variables directly into a string is up to 8% slower than string concatenation. this isn't the best reason for not using variables in strings, but it is one - the best reason is a better readable code if you use string concatenation (but thats only my opinion)