Home >Backend Development >PHP Tutorial >What are the situations when PHP functions return array type data?
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 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!