Consider the following PHP code. What will be printed when foo() is called?
<?php function foo() { return 5 + 3; } echo foo();
Remember that return sends a value back from the function.
The function foo() returns the sum of 5 and 3, which is 8. The echo prints this returned value.
Look at this PHP function. What value does it return when called with bar(4)?
<?php function bar($x) { if ($x > 5) { return $x * 2; } return $x + 2; } $result = bar(4); echo $result;
Check which return line runs for the input 4.
Since 4 is not greater than 5, the function returns 4 + 2 = 6.
Examine this PHP code. What error will it cause when run?
<?php function baz() { echo "Hello"; } $result = baz(); echo $result;
Consider what the function baz() returns by default.
The function baz() echoes "Hello" but does not have a return statement, so it returns null. echo $result; (null) outputs nothing and produces no error. The output is 'Hello'.
What will this PHP code print?
<?php function countdown($n) { if ($n <= 0) { return "Done!"; } return $n . " " . countdown($n - 1); } echo countdown(3);
Trace the function calls and how the strings join.
The function returns a string counting down from 3 to 1, then adds 'Done!'. So the output is '3 2 1 Done!'.
Consider this PHP code snippet. What is the value of $result after execution?
<?php function test() { return; return 10; } $result = test();
What happens when a function returns without a value?
The first return; exits the function immediately returning null. The second return 10; is never reached.