Alex Rivera | Logout

What is the difference between PHP echo and PHP return in plain English?

Asked 2012-02-22T01:03:24.893
54

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?

Edit
Report

2 Answers

3

echo renders the text etc into the document, return returns data from a function/method etc to whatever called it. If you echo a return, it'll render it (Assuming it's text/number etc - not an object etc).

answered 2012-02-22T01:05:23.273
2

Behind both functions you have a line, which toggles your output:

echo "<p>2 + 2 = ", add1(2, 2), "</p>";
echo "<p>2 + 2 = ", add2(2, 2), "</p>";

echo prints the value so you can read it. return returns the value to save in for example variables.

$result = add2(2, 2);
// do more with result ... ?
// output the result
echo $result;
answered 2012-02-22T01:07:58.917

Your Answer