This question already has an answer here:
Is there any why I can write this code by calling echo
once to get output as hello Sam
?
This is the PHP code :
<?php
function moo() {
echo 'Sam';
}
echo 'hello ' . moo();
?>
The output is Samhello
The parsing is R to L
. I can achieve the desired output by writing echo
on 2 separate lines as :
<?php
function moo() {
echo 'Sam';
}
echo 'hello ';
echo moo();
?>
but is there a way to do this in one line?
</div>
Instead of having the function echo
, just have it return the string you want to print. Then let the caller decide what to do with it - in this case, echo
it:
function moo() {
return 'Sam';
}
echo 'hello ' . moo();
Edit: Adding explanation (not the author of the answer) rather than leaving comment.
The difference between a "return" and an inline concat is that for the initial function (the echo statement) to work, it needs to run the function (in your code, it is moo() ) prior to outputting the initial echo statement.
This is no different to the following example:
echo number_format(get_something_from_database_which_is_a_number());
You want the function get_something_from_database_which_is_a_number()
to return the value prior to the number_format()
function to then format it nicely.
If you use a return
statement, the function itself will run, but then return
your string back to the initial function call (in your case an echo) statement.