php · level 1 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
hands the answer back so you can keep it.
So far your functions echo things. Echoing shows a value on the screen, and then it is gone. Your program cannot catch it, keep it or do maths with it.
To return a value, write return and the value. The call then turns into the answer, as if double(4) were the number 8. Store it, echo it or use it again.
A function with no return hands back , PHP's word for nothing at all. echo shows null as nothing, not even a space.
<?php
function double($number) {
return $number * 2;
}
$answer = double(4);
echo "$answer\n";
echo double($answer) . "\n"; Echoing is showing someone your answer, and return is handing it to them.
guess first
This one echoes instead. What will it show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
function double($number) {
echo $number * 2 . "\n";
}
$answer = double(4);
echo "Answer: $answer\n";
your turn
Your turn. Build a dog years machine.
In the first blank, type how many dog years each year counts as. People often say 7. In the second, type your dog's age, real or made up. Then run it.
fix it
Your score should double, but it stays at 5. Fix it!
- The function works and hands back 10. But does anything catch that answer?
- Line 6 calls
double, but the returned value falls on the floor. Store it in a variable. - Change line 6 to
$score = double($score);, then press run.
nailed it
your functions can hand back answers. :D
echoshows a value.returnhands it back to use.- A function with no
returnhands backnull. - Catch a returned value in a variable to keep it.
new words in your collection
- return
- null
This lesson isn’t saved. A free account remembers every lesson you finish.