Home >Backend Development >PHP Tutorial >What is the return value of a PHP function?
PHP functions can return scalar values, arrays, objects, or NULL. To declare a return value, use the return type hint in the function declaration. PHP does not support returning multiple values directly, but you can use an array or object to group them and return them.
Return value of PHP function
In PHP, a function can return a value, which can be any PHP data type , including:
Return value declaration
To declare the return value of a function, use return
in the function declaration Type hint:
function get_name(): string { return "John Doe"; }
This means that the get_name()
function will return a string.
Return multiple values
PHP does not support returning multiple values directly. However, you can use an array or object to group multiple values and return them.
Practical case
Consider the following function, which returns the largest element in an array:
function find_max(array $array): int { if (empty($array)) { return 0; } $max = $array[0]; foreach ($array as $element) { if ($element > $max) { $max = $element; } } return $max; } $array = [1, 3, 5, 2, 4]; $max_value = find_max($array); // 5
This function will $array
The maximum value of is stored in the $max_value
variable.
The above is the detailed content of What is the return value of a PHP function?. For more information, please follow other related articles on the PHP Chinese website!