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

Miguel Nunez
Miguel Nunez
3,266 Points

Why is it so hard for people to explain what a return means in php in simple terms?

98 percent of every one are having troubles explaining it in simple terms a return is blah blah so basically Values are returned. Values are returned ? What the heck does that mean "Values are returned" did the php code return borrowed some values from another code and did something to it and wants to give it back it makes it seems like it's metaphorically speaking john borrowed toms ball two days later he gave tom his ball back? what is the return code returning and why did it borrowed what it borrowed and what did it borrowed and from what code did it borrowed it from I'm getting confused with the grammar return as in borrowing something and returning it and return in the coding world please clear this up with short and simple answer even if you have to use a metaphor and why would I want to use a return and for what reason?

3 Answers

Think of a function as a "magic box" that does something for you when you "call upon it" by its name. Generally you would want to create a function to do a single task, this helps keep your code more flexible when you need to make changes.

Now this magic box could potentially do anything.

  • it could require that YOU must give it some input/arguments/parameters, these all are basically the same thing.
  • it could require no input from you, but generate something for you and give it back to you or return something.
  • it could take no input, it could return nothing back, and only print/echo something out.

Take for example this function. It has been awhile since I have done PHP but lets see if I can write some still haha.

 <?php
    function add_two($num){
        $new_num = $num + 2; // This is a value
        return $new_num; // we are returning that value
    }
 ?>

It is a simple function, its 1 and only job is to accept 1 input from YOU when you call it by its name. This "magic box's" name is add_two. So if we call it, it will want us to give it input which it will store into a variable called $num

Now whatever $num contains (hopefully an integer data type), it will do the calculation by adding 2 to whatever is contained in $num. Once that calculation has completed it is going to return THAT calculated value back to whatever called it.

So pretend I wrote that function and its part of some PHP script and later on I need to use that to ADD TWO to every item in an array of all these numbers I have.

<?php 
    // here is our function again...for reference
    function add_two($num){
        $new_num = $num + 2; // This is a value
        return $new_num; // we are returning that value
    }

    // pretend this list came from a database or a file.
    $numbers_list = array(2,6,10,14);

    foreach($numbers_list as $number):
        /* 
            Inside this block, we are looping over every item
            in the $numbers_list. So first time around is 2 then 6 then 10..etc.
            This could basically go on for hundreds, thoundsands or millions of times.

            Each time we do 1 iteration over this array, we are "calling upon our magic box named add_two.

            *NOTE 1*: We have 4 numbers in our array, so we will do 4 iterations.
            And each time we call add_two, it performs a calculation, stores the value, then returns THAT value.

            *NOTE 2*: add_two doesnt really have a clue what its going to receive for input until its called.
            It just knows that whatever it does get, it will store it in a temporary variable called $num.

            So first time around we give input of 2. Then 4 is the value returned
        */

        echo add_two($number) . ' ';
    endforeach;
    /*
        Loop would output:
        4 8 12 16
     */
?>

Now return is returning our value of 4 (if input was 2) back to where it was called from. So that line where it says echo add_two($number). add_two returned a value of 4 right back to the echo command.

I will stop there, let me know if that helps at all.

Miguel Nunez
Miguel Nunez
3,266 Points

Wow its making more sense now so if I did some math in a php function and I wanted the answer to be revealed to me I will have to use the return code to get my answer? Like for example 1+2 and I want my answer then I will use the return code to give me this right = 3 ? I know that's not php example but i'm trying to make that math example easy for me to understand what your really trying to say in easier terms for me to understand.

a function can be used to do almost anything, doing a Math calculation on something is just 1 thing it can do. Simple math problems are easier to understand for examples though.

For example you could make a function add two numbers (YOU GIVE IT) together and divide by two then RETURN you that answer (or value)

like this:

 <?php
    // Now our function is EXPECTING 2 inputs
    // The first item passed will get set to $num1
    // The second item passed will get set to $num2

    function add_and_divide_by_two($num1, $num2){
        $new_value = ($num1 + $num2) / 2; // this is our calculated VALUE
        // the parenthesis around $num1 and $num2 are ensuring, 
        // we total up before we divide. Order of operations apply here, just like in Math class.
        return $new_value; // return the VALUE
    }


    $number1 = 6; // storing integer 6 in variable
    $number2 = 8; // storing integer 8 in variable

    /*
        Here we are passing both variables that each hold a number.
        $number1 is holding a 6
        $number2 is holding an 8

        But this time we are setting $answer variable equal to 
        whatever is returned from our 'magic box' named add_and_divide_by_two()
     */
    $answer = add_and_divide_by_two($number1, $number2);

    /* 
        Since we can access our 'magic box' that does some math for us by its name.
        We can call it multiple times passing it different things.

        This time I wont store the numbers in a variable, I will directly pass them in.
        The order matters though.

        Because our function looks like this:

        function add_and_divide_by_two($num1, $num2)

        10 gets passed to our function, then our function temporarily stores it in a variable called $num1
        20 gets stored into $num2 because we passed it as the 2nd item.
    */
    $another_answer = add_and_divide_by_two(10, 20);

    echo $answer . ' ';
    echo $another_answer . ' ';

      /*
          We passed in a 6 and 8 for the $answer variable. 6 + 8 = 14 then divide by 2 is: 7
          We passed in a 10 and 20 for $another_answer. 10 + 20 = 30 then divide by 2 is: 15

          Output for these two echo statements are:
           7 15
      */

?>
Miguel Nunez
Miguel Nunez
3,266 Points

Sorry if this sounds rude but can you just give me a straight answer to what I said about my math statement I said about if the return value will be 3? I just tend to get confused when people respond with a very long answer rather than a direct short answer.

Yes if you write a function that does a math calculation like you said: 1+3. if at the end of your function if you return 1+3;

That function will "give back" that answer. Which will be 4. But it hands it back to the line that originally called it, so if you set a variable equal to a function. That variable will equal whatever is returned by that function. :-)

Kevin Gates
Kevin Gates
15,052 Points

This should be marked as "Best Answer".

Miguel Nunez
Miguel Nunez
3,266 Points

Thanks Chris Howell sorry about the other message its just my head hurted a lot lol so I know now what returns are all about now example of what you said the 4 will be the return value ok it makes sense now thank you :-)

So now the absolute BEST thing you can do, is go play with some code to reinforce this new understanding of return statements....until you reach another point where you get stuck again!

Best way to learn in programming is playing with code. One thing is for sure, whether you are getting errors or your code is producing wrong results or they are producing the right ones. You are learning or reinforcing what you learned. So go play with return statements! :)

Miguel Nunez
Miguel Nunez
3,266 Points

Thanks alot Chris :-} I have one more question man what and I know now what a return means now So I notice some examples like for example math situations will tend to give me a situation that equals the answer so for example 1+1= 2 I notice echo and a return gives the same answer and response when I see an execution of it if they as so different what are they doing given the same results and same effects why would I bother with a return if I can just do the same thing with just use an echo all the time.

No problem, it would be hard to explain these differences out. But easier to physically show you.

Are you familiar with using Team Treehouse's Workspaces?

If so I threw together a workspace that you can fork then you can Preview it in your own.

After you have forked over to your Workspace and click Preview it should open index.php up like a webpage and show you what the functions are outputting.

Be sure to check the example_functions.php file. Even add your own functions or change mine and see what happens.

PHP Workspace

Keep these things in mind:

echo statement is for outputting something.

return statement is for "handing" back something to whatever called it.