Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP function returning two arrays

I have a function and I need it to return two arrays.

I know a function can only return one variable .. is there a way to return my two arrays?

If I concatenate them, how can I separate them cleanly when out of the function?

like image 606
lleoun Avatar asked Nov 22 '12 08:11

lleoun


People also ask

How can I return two arrays from a function in PHP?

$arr1 = array(); $arr2 = foobar($arr1); This won't be useful if you always need to return two arrays, but it can be used to always return one array and return the other only in certain cases.

Can a PHP function return 2 values?

PHP doesn't support to return multiple values in a function. Inside a function when the first return statement is executed, it will direct control back to the calling function and second return statement will never get executed.

How do you return 3 arrays from a function?

$data = array( $icon, $fa, $oi ); $return $data; However, if you want assign returned value to three arrays, you can do it in this way: list( $icon, $fa, $oi ) = svca_icon_fields(); then you will have three different arrays (you can change $icon etc with your preferred array names).

Can a PHP function return an array?

In PHP you can return one and only one value from your user functions, but you are able to make that single value an array, thereby allowing you to return many values.


2 Answers

No need to concatenate: just return array of two arrays, like this:

function foo() {
    return array($firstArray, $secondArray);
}

... then you will be able to assign these arrays to the local variables with list, like this:

list($firstArray, $secondArray) = foo();

And if you work with PHP 5.4, you can use array shortcut syntax here as well:

function foo54() {
    return [$firstArray, $secondArray];
}
like image 52
raina77ow Avatar answered Oct 22 '22 14:10

raina77ow


I think raina77ow's answer adequately answers your question. Another option to consider is to use write parameters.

function foobar(array &$arr1 = null)
{
    if (null !== $arr1) {
        $arr1 = array(1, 2, 3);
    }

    return array(4, 5, 6);
}

Then, to call:

$arr1 = array();
$arr2 = foobar($arr1);

This won't be useful if you always need to return two arrays, but it can be used to always return one array and return the other only in certain cases.

like image 20
Ja͢ck Avatar answered Oct 22 '22 14:10

Ja͢ck