我有一个数组:

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

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

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

我该怎么做呢?


当前回答

一行闭行,复制,重置:

<?php

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

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

输出:

apple

或者更短的短箭头函数:

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

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

其他回答

来自Laravel的助手:

function head($array)
{
    return reset($array);
}

数组是按值传递给函数的,reset()会影响数组副本的内部指针,而不会触及原始数组 数组(注意,如果数组为空,则返回false)。

使用的例子:

$data = ['foo', 'bar', 'baz'];

current($data); // foo
next($data); // bar
head($data); // foo
next($data); // baz

这里还有一个选择。它稍微快一点,但更有趣。如果数组为空,它可以很容易地更改默认值:

function head($array, $default = null)
{
    foreach ($array as $item) {
        return $item;
    }
    return $default;
}

为了记录,这是我的另一个答案,对于数组的最后一个元素。

这有点晚了,但我遇到了一个问题,我的数组包含数组元素作为其子元素,因此我不能获得第一个数组元素的字符串表示形式。通过使用PHP的current()函数,我管理了这个:

<?php
    $original = array(4 => array('one', 'two'), 7 => array('three', 'four'));
    reset($original);  // to reset the internal array pointer...
    $first_element = current($original);  // get the current element...
?>

感谢所有当前的解决方案帮助我得到这个答案,我希望这能帮助到别人!

一行闭行,复制,重置:

<?php

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

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

输出:

apple

或者更短的短箭头函数:

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

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

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

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

只是做的事:

array_shift(array_slice($array,0,1));