我有一个数组:

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

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

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

我该怎么做呢?


当前回答

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

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

其他回答

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

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

一行闭行,复制,重置:

<?php

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

echo (function() use ($fruits) { return reset($fruits); })();

输出:

apple

或者更短的短箭头函数:

echo (fn() => reset($fruits))();

这使用如上所述的按值变量绑定。两者都不会改变原来的指针。

有两个解决方案。

解决方案1 -使用钥匙。你没有说你不能用它。:)

<?php
    // Get the first element of this array.
    $array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );

    // Gets the first element by key
    $result = $array[4];

    // Expected result: string apple
    assert('$result === "apple" /* Expected result: string apple. */');
?>

解决方案2 - array_flip() + key()

<?php
    // Get first element of this array. Expected result: string apple
    $array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );

    // Turn values to keys
    $array = array_flip($array);

    // You might thrown a reset in just to make sure
    // that the array pointer is at the first element.
    // Also, reset returns the first element.
    // reset($myArray);

    // Return the first key
    $firstKey = key($array);

    assert('$firstKey === "apple" /* Expected result: string apple. */');
?>

解决方案3 - array_keys()

echo $array[array_keys($array)[0]];

一些数组不能与list、reset或current等函数一起使用。也许它们是“人造”数组——例如,部分实现了ArrayIterator。

如果你想拉出第一个值而不考虑数组,你可以短路迭代器:

foreach($array_with_unknown_keys as $value) break;

然后你的值将在$value中可用,循环将在第一次迭代后中断。这比将一个潜在的大数组复制到array_unshift(array_values($arr))这样的函数更有效。

你也可以用这种方式获取钥匙:

foreach($array_with_unknown_keys as $key=>$value) break;

如果你从函数中调用这个函数,只要提前返回:

function grab_first($arr) {
    foreach($arr as $value) return $value;
}

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

$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