我有一个数组:

阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)

我想要得到这个数组的第一个元素。预期结果:串苹果

一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。

我该怎么做呢?


当前回答

<?php
    $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
    echo array_values($arr)[0]; // Outputs: Apple
?>

其他的例子:

<?php
    $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
    echo current($arr); // Outputs: Apple
    echo reset($arr); // Outputs: Apple
    echo next($arr); // Outputs: Ball
    echo current($arr); // Outputs: Ball
    echo reset($arr); // Outputs: Apple
?>

其他回答

我认为使用array_values是最好的选择。你可以从函数的结果中返回下标0处的值,得到'apple'。

查找数组中的第一个和最后一个项:

// Get the first item in the array
print $array[0]; // Prints 1

// Get the last item in the array
print end($array);

我不喜欢摆弄数组的内部指针,但是用array_keys()或array_values()构建第二个数组也很低效,所以我通常定义这个:

function array_first(array $f) {
    foreach ($f as $v) {
        return $v;
    }
    throw new Exception('array was empty');
}

这里有太多的答案,选择的答案将适用于大多数情况。

在我的例子中,我有一个2D数组,array_values出于某种奇怪的原因删除了内部数组上的键。所以我的结论是:

$keys = array_keys($myArray); // Fetches all the keys
$firstElement = $myArray[$keys[0]]; // Get the first element using first key

如果你正在使用Laravel,你可以做:

$array = ['a', 'b', 'c'];
$first = collect($array)->first();