PHP 函数返回两个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13508572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:36:19  来源:igfitidea点击:

PHP function returning two arrays

phparraysfunctionreturnconcatenation

提问by lleoun

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?

如果我将它们连接起来,在函数之外如何将它们干净地分开?

回答by raina77ow

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将这些数组分配给局部变量,如下所示:

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

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

如果您使用 PHP 5.4,您也可以在此处使用数组快捷方式语法:

function foo54() {
    return [$firstArray, $secondArray];
}

回答by Ja?ck

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

我认为raina77ow的回答足以回答你的问题。要考虑的另一个选项是使用写入参数。

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 alwaysneed to return two arrays, but it can be used to always return one array and return the other only in certain cases.

如果您总是需要返回两个数组,这将没有用,但它可用于始终返回一个数组并仅在某些情况下返回另一个数组。