How to get a set of variables returned by a function using an array

Return and pass arrays with PHP functions

A PHP function can accept an array argument and can return an array. Modern PHP can also declare array parameter and return types where appropriate.

function words(string $text): array {
    return explode(' ', trim($text));
}

$result = words('Hello welcome to plus2net');
foreach ($result as $key => $value) {
    echo "$key -> $value
"; }

The old split() and each() functions are removed from current PHP; use explode()/preg_split() and foreach instead.

From a function we can get back a set of variables by using an array. A function returns any variable to the main script by using return statement. Here we will try to return a set of variables by using an array. Our main script will receive the array and we will use while each statement to display all elements of an array.

We will change a script a bit and try to pass ( as input ) a string to the function. This string we will break by using explode() and create an array. This array we will return to main script for displaying.

Here is the code ..
function test($my_string){
// creating an array by explode()
$my_array=explode(" ", $my_string);
return $my_array; // returning the array
}

// sending a string to function as input //
$collect_array=test("Hello welcome to plus2net");

// displaying the elements of the collected array
foreach ($collect_array as $key => $val) {
echo "$key -> $val <br>";
}

Passing an array as input to PHP function

Above we have discussed how to return an array from a function. Now we will discuss how to input or pass an array to a function.

We will break an string and create an array. This created array we will pass as input to the function. To test the array inside the function we will display it by using while each command.

Here is the code.
function test($my_array){
foreach ($my_array as $key => $val) {
echo "$key -> $val <br>";
} 

}
$collect_array=explode(" ", "Hello welcome to plus2net");
test($collect_array);

ARRAY REFERENCE Applying user function to elements of an array


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer