Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 20 down vote accepted

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];
}
share|improve this answer
    
thanks very much! –  lleoun Nov 22 '12 at 8:55
1  
+1 to gain nice answer :) –  Ja͢ck Nov 23 '12 at 11:45
    
Excellent, thank you! –  James Huckabone Oct 7 '13 at 17:18

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.