Home >Backend Development >PHP Tutorial >What is the return value of a PHP function?

What is the return value of a PHP function?

王林
王林Original
2024-04-10 11:15:02985browse

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.

PHP 函数的返回值是什么?

Return value of PHP function

In PHP, a function can return a value, which can be any PHP data type , including:

  • Scalar value (string, integer, floating point number, Boolean value)
  • Array
  • Object
  • NULL

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn