我有一个数组:

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

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

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

我该怎么做呢?


当前回答

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

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

 /**
 * 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));
}

其他回答

PHP 7.3添加了两个函数,用于直接获取数组的第一个和最后一个键,而无需修改原始数组,也无需创建任何临时对象:

array_key_first array_key_last

有几种方法可以为PHP 7.3.0之前的版本提供此功能。可以使用array_keys(),但这可能相当低效。也可以使用reset()和key(),但这可能会改变内部数组指针。一个有效的解决方案,它不改变内部数组指针,写为polyfill:

<?php
if (!function_exists('array_key_first')) {
    function array_key_first($arr) {
        foreach($arr as $key => $unused) {
            return $key;
        }
        return NULL;
    }
}

if (!function_exists('array_key_last')) {
    function array_key_last($arr) {
        return array_key_first(array_reverse($arr, true));
    }
}
?>

我输入echo current($array)

当前数组($)

根据PHP手册,返回数组的第一个元素。

每个数组都有一个指向其“当前”元素的内部指针,该指针被初始化为插入数组的第一个元素。

所以它一直工作,直到你重新定位数组指针,否则你将不得不使用reset(),它将倒带数组并返回数组的第一个元素

根据PHP手动复位。

Reset()将数组的内部指针倒回到第一个元素,并返回第一个数组元素的值。

current()和reset()的示例

$array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "<br />\n"; // "step one"

//Forward the array pointer and then reset it

// skip two steps
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"

// reset pointer, start again on step one
echo reset($array) . "<br />\n"; // "step one"

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

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

你可以通过下面的代码获取第一个元素:

$array_key_set = array_keys($array);
$first_element = $array[$array_key_set[0]];

或者使用:

$i=0;
foreach($array as $arr)
{
  if($i==0)
  {
    $first_element=$arr;
    break;
  }
 $i++;
}
echo $first_element;