Concatenate PHP Function Output to a String Like Variables

Concatenate PHP function output to a string like variables

You can concatenate with . operator:

echo "I say  " . strtolower($x) . " to all of you.";

Or just :

echo "I say  ", strtolower($x), " to all of you.";

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.

PHP string concatenation

Just use . for concatenating.
And you missed out the $personCount increment!

while ($personCount < 10) {
$result .= $personCount . ' people';
$personCount++;
}

echo $result;

Return concatenated string from function in PHP

$my_array = array ("id" => "test");

$test = "First part " . $my_array['id'];
echo $test; // <-- returns "First part test"

function concatenate($my_array){
$test_2 = "First part " . $my_array['id'];
return $test_2;
}

$use_function = concatenate($my_array);
echo $use_function;

It's a minor mistake.. Please be careful, while calling function..

How to concatenate strings with function calls while using echo?

echo '<li><a href="', the_permalink(), '">', the_title(), '</a></li>';


Related Topics



Leave a reply



Submit