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?
Echo is for display, while return is used to store a value, which may or may not be used for display or other use.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print .
PHP echo statement can be used to print the string, multi-line strings, escaping characters, variable, array, etc. Some important points that you must know about the echo statement are: echo is a statement, which is used to display the output. echo can be used with or without parentheses: echo(), and echo.
The print and echo are both language constructs to display strings. The echo has a void return type, whereas print has a return value of 1 so it can be used in expressions. The print_r is used to display human-readable information about a variable.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With