Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP PHP Functions Function Returns and More Returning Values

Ezra John Alvarez
Ezra John Alvarez
557 Points

When is the right time to use return vs echo?

Hi,

How do I know that I need to use return on this or use echo on this?

Like, when is the right time to use return vs echo? If you can give real life situation, much appreciated.

Thanks!!!

3 Answers

You only use echo when you want to print something onto the screen or within the markup i.e text on the screen, path to an image or title on the top of an html page. Return is commonly used in a function to return the output of the function i.e.

/*Function to return a value*/
public function returnName($name){

/* See here i'm returning the output of the function*/
return "Hello " . $name . " mate!";
}

/*Here i will echo (display) the output of the function onto the screen*/
$greeting = returnName("Billy");

echo $greeting;

/*********OUTPUT*********/
Hello Billy mate
/*********OUTPUT*********/
Ezra John Alvarez
Ezra John Alvarez
557 Points

Hi Tunde, thanks for this! Cheers!

Lolo Handricks
seal-mask
.a{fill-rule:evenodd;}techdegree
Lolo Handricks
Front End Web Development Techdegree Student 10,706 Points

But wouldn't we still be able to achieve the above by using echo though?

function returnName($name){

echo "Hello $name mate!"; }

returnName('Billy');

/******OUTPUT***/ Hello Billy mate /***OUTPUT******/

Tunde Adegoroye, Are you able to explain why you would use return in this instance instead of echo?

I think the reason one might use return in this case instead of echo would be the ability to assign the returned result to a variable in order to use that in more than one part of the application, possibly never being displayed at all but being used in a comparator, for example. This function, in particular, doesn't seem intuitive for that purpose (I think that is partially due to the sort of confusing name of the function, think of it as function greet($name) instead).