Yes, I have googled this question and even referred to my textbook (PHP by Don Gosselin) but I seriously can't seem to understand the explanation.
From my understanding:
echo = shows the final result of a function
return = returns the value from a function
I applied both echo
and return
in the following functions I can't see the difference or the 'effectiveness' of using return
instead of echo
.
<?php
echo "<h1 style='font-family:Helvetica; color:red'>Using <em>echo</em></h1>";
function add1($x, $y){
$total = $x + $y;
echo $total;
}
echo "<p>2 + 2 = ", add1(2, 2), "</p>";
echo "<h1 style='font-family:Helvetica; color:red'>Using <em>return</em></h1>";
function add2($x, $y){
$total = $x + $y;
return $total;
}
echo "<p>2 + 2 = ", add2(2, 2), "</p>";
?>
Both display the result! What am I not understanding?
I'm going to give a completely non-technical answer on this one.
Let's say that there is a girl named Sally Function. You want to know if she likes you or not. So since you're in grade school you decide to pass Sally a note (call the function with parameters) asking her if she likes you or not. Now what you plan on doing is asking her this and then telling everyone what she tells you. Instead, you ask her and then she tells everyone. This is equivalent to returning (you getting the information and doing something with it) vs her echoing (telling everyone without you having any control).
In your case what is happening is that when Sally echo
s she is taking the control from you and saying "I'm going to tell people this right now" instead of you being able to take her response and do what you wanted to do with it. The end result is, however, that you were telling people at the same time since you were echoing what she had already echoed but didn't return (she cut you off in the middle of you telling your class if she liked you or not)