So far, our functions have printed text. A more useful function returns a value so the caller can decide what to do with it.
<?php
function add(int $a, int $b): int
{
return $a + $b;
}
$result = add(3, 4);
echo $result;
7
return does two things: it sends the value back, and it ends the function immediately.
return vs echo
echo | return | |
|---|---|---|
| Purpose | Shows text | Gives a value back |
| Caller can store the value | No | Yes |
| Ends the function | No | Yes |
A function that only prints cannot be reused in a calculation. A function that returns can be used anywhere.
<?php
function priceWithTax(float $price): float
{
return $price * 1.18;
}
$total = priceWithTax(100) + priceWithTax(200);
echo $total;
354
Code after return never runs
<?php
function test(): string
{
return "first";
echo "never printed";
}
echo test();
first
Early return
Use return early to handle special cases and keep the rest of the code simple.
<?php
function divide(float $a, float $b): float|string
{
if ($b === 0.0) {
return "Cannot divide by zero";
}
return $a / $b;
}
echo divide(10, 4) . "\n";
echo divide(5, 0);
2.5
Cannot divide by zero
Return several values
A function returns only one value, but that value can be an array.
<?php
function minMax(array $numbers): array
{
return [min($numbers), max($numbers)];
}
[$lowest, $highest] = minMax([4, 9, 2, 7]);
echo "Lowest $lowest, highest $highest";
Lowest 2, highest 9
An associative array is clearer when there are many values.
<?php
function stats(array $numbers): array
{
return [
"sum" => array_sum($numbers),
"average" => array_sum($numbers) / count($numbers),
];
}
$result = stats([2, 4, 6]);
echo "Sum: {$result['sum']}, average: {$result['average']}";
Sum: 12, average: 4
No return means null
A function with no return gives back null.
<?php
function noReturn(): void
{
$x = 5;
}
var_dump(noReturn());
NULL
Exercise: a square function
Write square(int $n): int that returns $n * $n, and use it to print the square of 9.
Show a possible solution
<?php
function square(int $n): int
{
return $n * $n;
}
echo square(9);
81