Home >Backend Development >PHP Tutorial >What are the situations when PHP functions return array type data?

What are the situations when PHP functions return array type data?

WBOY
WBOYOriginal
2024-04-20 14:42:01752browse

PHP functions may encounter the following situations when returning array type data: if the return array type is explicitly declared, the array will be returned directly; returning a null value will cause an error; calling a function that receives an array can return another array.

PHP 函数返回数组类型的数据有哪些情况?

PHP function returns array type data

In PHP, when a function returns array type data, it usually encounters To the following situation:

1. Explicit array type hint

When the function signature explicitly declares that the returned data type is an array, the function will return an array. For example:

function get_data(): array
{
    return ['name' => 'John', 'age' => 30];
}

2. Return null

Some functions may return null values, for example when the required data cannot be found. However, when a function is declared to return an array type, returning null raises an error.

3. Call the function that receives the array

PHP also provides some functions (such as array_filter() and array_map() ), they receive an array as argument and return another array. The following example shows how to use the array_filter() function:

function filter_numbers(array $arr)
{
    return array_filter($arr, function($item) {
        return is_numeric($item);
    });
}

$numbers = [1, 2, 'a', 4, 'b'];
$result = filter_numbers($numbers);
// $result 现在是一个仅包含数字的数组

Practical case: Get a list of files

Consider a method to get a list of files in a specified directory Function:

function get_files(string $dir): array
{
    if (!is_dir($dir)) {
        throw new InvalidArgumentException("$dir is not a valid directory.");
    }

    $files = scandir($dir);
    if ($files === false) {
        throw new RuntimeException("Failed to scan directory.");
    }

    foreach ($files as $key => $file) {
        if ($file == '.' || $file == '..') {
            unset($files[$key]);
        }
    }

    return array_values($files);
}

This function returns an array containing the file names in the directory. It handles invalid directories, failed directory scans, and dereferences of the current directory and parent directories.

The above is the detailed content of What are the situations when PHP functions return array type data?. 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