PHP Functions
Declare typed parameters and return values.
On this page
PHP basics.
- Declare typed parameters and return values.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
<?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";86 1.5
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
<?phpfunction average(array $values): float { return array_sum($values) / count($values);} echo average([82, 91, 76, 95]), "\n";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 |
Behind the scenes
How PHP processes this code
The PHP runtime executes the script. echo writes to the response or terminal output.
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.