How to make PHP functions return an array
A PHP function can return only one value using the return statement.
The return value from a PHP function can be of any type, including arrays and objects.
To return an array from a PHP function:
- you can create the array next to the
returnkeyword - you can return a variable of array type
Here’s an example of making a PHP function return an array:
<?php
// ๐ 1. return a literal array
function get_names() {
return ["Nathan", "Jenny"];
}
$names = get_names();
print $names[0]. "\r\n"; // Nathan
print $names[1]. "\r\n"; // Jenny
// ๐ 2. return an array variable
function get_weathers() {
$weathers = ["Sunny", "Cloudy", "Rainy"];
return $weathers;
}
$var = get_weathers();
print $var[0]. "\r\n"; // Sunny
print $var[1]; // Cloudy
?>
As you can see, it’s very easy to make a PHP function returns an array.
More PHP tutorials
See allPHP
PHP form validation basic example
Dec 22, 2022
PHP
PHP validate email address (with code examples)
Dec 22, 2022
PHP
How to redirect using PHP with code examples
Dec 22, 2022
PHP
Handling form data using PHP (GET and POST)
Dec 21, 2022
PHP
How to fix Wordpress PHP error missing MySQL extension
Dec 21, 2022