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
Displaying Multiple Lines of a File, Never Repeating
Cannot Call Function SQLsrv_Connect()
Php: Type Hinting - Difference Between 'Closure' and 'Callable'
How to Expire PHP Session If User Is Inactive for 15 Mins
PHP Allocate Color Without Image Resource
Check to See If an Email Is Already in the Database Using Prepared Statements
How to Get List of Defined Namespaces
How Is MVC Supposed to Work in Codeigniter
Pass PHP Variable to Bootstrap Modal
Using Preg_Split with Multiple Spaces
Array Merge on Multidimensional Array
Replace &Nbsp; Characters That Are Hidden in Text
Simple Form Not Sending Data via _Post