我有一个数组:

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

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

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

我该怎么做呢?


当前回答

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

array_key_first array_key_last

除了语义上有意义外,这些函数甚至不移动数组指针(就像foreach那样)。

有了键,就可以直接通过键获取值。


示例(它们都需要PHP 7.3+)

获取第一个/最后一个键和值:

$my_array = ['IT', 'rules', 'the', 'world'];

$first_key = array_key_first($my_array);
$first_value = $my_array[$first_key];

$last_key = array_key_last($my_array);
$last_value = $my_array[$last_key];

获取第一个/最后一个值为一行,假设数组不能为空:

$first_value = $my_array[ array_key_first($my_array) ];

$last_value = $my_array[ array_key_last($my_array) ];

获取第一个/最后一个值为一行程序,默认为空数组:

$first_value = empty($my_array) ? 'default' : $my_array[ array_key_first($my_array) ];

$last_value = empty($my_array) ? 'default' : $my_array[ array_key_last($my_array) ];

其他回答

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

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

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

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

$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

没有人建议使用ArrayIterator类:

$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$first_element = (new ArrayIterator($array))->current();
echo $first_element; //'apple'

绕过OP的参照规定。

有两个解决方案。

解决方案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]];

当前数组($)

根据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"