我有一个数组:

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

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

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

我该怎么做呢?


当前回答

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

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

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

其他回答

有两个解决方案。

解决方案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]];
$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key

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

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

Use:

$first = array_slice($array, 0, 1);  
$val= $first[0];

默认情况下,array_slice不保留键,所以我们可以安全地使用0作为索引。

只是做的事:

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