我有一个数组:

阵列(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);

其他回答

没有人建议使用ArrayIterator类:

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

绕过OP的参照规定。

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

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

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

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

当前数组($)

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

这是一个结合了array_slice和implode的例子:

$arr = array(1, 2, 3);
echo implode(array_slice($arr, 0, 1));
// Outputs 1

/*---------------------------------*/

$arr = array(
    'key_1' => 'One',
    'key_2' => 'Two',
    'key_3' => 'Three',
);
echo implode(array_slice($arr, 0, 1));
// Outputs One