Can You Append Strings to Variables in PHP

Can you append strings to variables in PHP?

This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator:

for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';

How can I concatenate a string with variables in PHP?

Try this:

// list is a string variable
$list = "";

// total number of seats in a Bus
$setnum = 10;
$list = "";
for($i = 0; $i < 10; $i++) {
// i trying to concatenate string like 10,11,12,13,14
$list .= ($i + $setnum) . ', ';
}

echo $list;

PHP append same string to multiple other strings in one line?

There is currently no syntax of any specific shorthand to do this on pure variables.

There are various ways this can be done with array values and looping but this would involve adding code lines to the script and mitigate the intention to DRY down the original code.

PHP - concatenate or directly insert variables in string

Between those two syntaxes, you should really choose the one you prefer :-)

Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.

The result will be the same; and even if there are performance implications, those won't matter 1.


As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:

echo "Welcome $names!";

PHP will interpret your code as if you were trying to use the $names variable -- which doesn't exist.
- note that it will only work if you use "" not '' for your string.

That day, you'll need to use {}:

echo "Welcome {$name}s!"

No need to fallback to concatenations.


Also note that your first syntax:

echo "Welcome ".$name."!";

Could probably be optimized, avoiding concatenations, using:

echo "Welcome ", $name, "!";

(But, as I said earlier, this doesn't matter much...)


1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.

Concatenate HTML string and variable in PHP

Use single quotes for raw HTML and curly braces around PHP variables. Like so;

$content = "<meta property='foo' url='{$url}' name='{$name}'>";

Appending to / concatenating multiple strings in one call in PHP?

There is no way to concatenate 'in one call' like this in php outside making your own function and calling it. Appending operators work on only one variable.



Related Topics



Leave a reply



Submit