我有一个数组:

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

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

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

我该怎么做呢?


当前回答

没有人建议使用ArrayIterator类:

$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$first_element = (new ArrayIterator($array))->current();
echo $first_element; //'apple'

绕过OP的参照规定。

其他回答

大部分都有用!但是对于一个快速的单线(低资源)呼叫:

$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
echo $array[key($array)];

// key($array) -> will return the first key (which is 4 in this example)

虽然这是可行的,而且还不错,但请参阅我的额外答案: https://stackoverflow.com/a/48410351/1804013

$arr = $array = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // echoes 'apple'

如果不想丢失当前指针的位置,只需为数组创建一个别名。

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

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

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

一种简单的方法是:

$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );

function get_first ($foo) {
    foreach ($foo as $k=>$v){
        return $v;
    }
}

print get_first($foo);

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

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

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