+ 2
What is the difference between 'echo' and "return''
Related to PHP
3 Answers
+ 8
echo outputs content to the console or the web browser.
Example:
echo "Hey, this is now showing up on your screen!";
return returns a value at the end of a function or method.
Example:
function my_function() {
return "Always returns this"; }
echo my_function();
// displays "Always returns this"
+ 4
When you have a function (or method in OOP), the code executes within the function but does not send anything out unless you have a return. The return itself does not display anywhere. You can assign it to a variable elsewhere for more to be done to it, you can echo it, or you can just ignore it. For example, you could do this with your function:
<?php
function value() {
$number = 1; return $number;
}
$val = value(); if ($val !== 1) {
echo "The number is not 1."; }
elseif ($val === 1) {
echo "The number is 1."; } else {
echo "There was an error. The number is $val."; }
As you get more into functions you will learn to pass values into the function that will make my example a little more meaningful. But you can see how using return allows you to then analyze the result of the function with more code. When you use databases, you often return an array of values derived from the database :)
0
echo -> output the contents in your code
return-> returns the last value of a function