PHP - Concatenate or Directly Insert Variables in String

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}'>";

PHP string concat with slashes and variables

If the below is working fine

rclone copy /media/storage/Events/01//999/001 events:testing-events-lowres/Events/01/999/001 --size-only --exclude /HiRes/* --include /Thumbs/* --include /Preview/* -P --checkers 64 --transfers 8 --config /home/admin/.config/rclone/rclone.conf -v --log-file=/www/html/admin/scripts/upload_status/001.json --use-json-log

Then below is the related PHP code, assuming your variables will contain correct values. You are doing some mistake while concatenating, not using proper . (dots) and " (quotes).

exec("rclone copy ".$baseDir."/".$mainEventCode."/".$eventCode." events:testing-events-lowres/Events/01/".$mainEventCode."/".$eventCode." --size-only --exclude /HiRes/* --include /Thumbs/* --include /Preview/* -P --checkers 64 --transfers 8 --config /www/html/admin/scrips/rclone.conf -v --log-file=$directoryName/".$eventCode.".json --use-json-log");

PHP: variables in strings without concatenation

In php you can escape variables like so

echo "Hello, ${var}'s head is big";

or like

echo "Hello, {$var}'s head is big";

Reference here under escape character section

Inserting variable in string

You have to use double quoutes for variable interpolation to work in PHP.
Because you are creating JSON it doesnt seem to be a solution so you should:

Create JSON structure as PHP array and use json_encode to transform to string

or

Use sprintf to interpolate variable in your string like:

$json = sprintf('{
"order": {
"items": [
{
"reference": "webshop",
"name": "%s",
"quantity": 1,
}
]
}
}', "Value");


Related Topics



Leave a reply



Submit