是否有一种方法可以在一行中从函数返回数组键


Is there a way to return an array key from a function in one line?

例如:

$str = 'one-two-three';
$one = explode('-', $str);

有没有办法使$ 1等于" 1 "而不做$one = $one[0] ?

当然,使用list():

list($one,$two,$three) = explode('-', $str);
echo $one;
// one

list()用于多赋值,它不像能够直接从函数调用中解引用数组元素那样好,也不像Python的多赋值那样方便,但它可以完成任务。

在PHP 5.4中,我们将能够直接从函数调用中解引用,如下所示:

// Coming in 5.4...
explode("-", $str)[0]

您也可以使用合适的函数:

 $one = strtok($str, "-");

参见strtok()strstr()与第三个参数

试试这个

list($one, $two, $three) = explode('-', $str);

foreach($one as $number) {
    $$number = $number;
}