PHP Functions
Declare typed parameters and return values.
PHP
<?php
function average(array $values): float {
return array_sum($values) / count($values);
}
echo average([82, 91, 76, 95]), "\n";
echo round(average([1, 2]), 1), "\n";Output
86 1.5
Explanation
A function is declared with function, and its parameters and return type can carry type declarations such as array and float. PHP then checks the values when the function runs.
array_sum adds the numbers in an array and count returns how many there are. The echo statement accepts several comma-separated values. A float that has no fractional part prints without a decimal point, so 86.0 is shown as 86.
Explore the dry run
Guided walkthroughReady
1
<?php2
function average(array $values): float {3
return array_sum($values) / count($values);4
}5
6
echo average([82, 91, 76, 95]), "\n";7
echo round(average([1, 2]), 1), "\n";Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Accept an array and return a float. | — | — | |
| 344 / 4 is 86.0, echoed as 86. | return = 86.0 | 86 | |
| 3 / 2 is 1.5; round keeps one decimal. | return = 1.5 | 86 1.5 |
Cost and common mistakes
O(n) time and O(1) extra space.
- Dividing by count([]) throws DivisionByZeroError in PHP 8; check for an empty array first.
- Without declare(strict_types=1), PHP may convert scalar arguments silently, such as "5" to 5.
Try it yourself
Predict average([10, 20, 31]).
Reveal answer and reasoning
The sum is 61 and 61 / 3 is 20.333333333333, so that is what echo prints.