我有一个数组:

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

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

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

我该怎么做呢?


当前回答

假设:

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

只使用:

$array[key($array)]

得到第一个元素或

key($array)

得到第一把钥匙。

如果你想删除第一个,你也可以取消它的链接。

其他回答

对Sarfraz发布的内容做了一个小改动:

$array = array(1, 2, 3, 4, 5);
$output = array_slice($array, 0, 1);
print_r ($output);

来自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

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

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

输出:

apple

或者更短的短箭头函数:

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

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

同样值得记住的是您执行此操作的上下文,因为详尽的检查可能是昂贵的,而且并不总是必要的。

例如,这个解决方案在我使用它的情况下工作得很好(但显然不能在所有情况下都依赖它……)

 /**
 * A quick and dirty way to determine whether the passed in array is associative or not, assuming that either:<br/>
 * <br/>
 * 1) All the keys are strings - i.e. associative<br/>
 * or<br/>
 * 2) All the keys are numeric - i.e. not associative<br/>
 *
 * @param array $objects
 * @return boolean
 */
private function isAssociativeArray(array $objects)
{
    // This isn't true in the general case, but it's a close enough (and quick) approximation for the context in
    // which we're using it.

    reset($objects);
    return count($objects) > 0 && is_string(key($objects));
}

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