我有一个数组:
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
我想要得到这个数组的第一个元素。预期结果:串苹果
一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。
我该怎么做呢?
我有一个数组:
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
我想要得到这个数组的第一个元素。预期结果:串苹果
一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。
我该怎么做呢?
当前回答
假设:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
只使用:
$array[key($array)]
得到第一个元素或
key($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"
一行闭行,复制,重置:
<?php
$fruits = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
echo (function() use ($fruits) { return reset($fruits); })();
输出:
apple
或者更短的短箭头函数:
echo (fn() => reset($fruits))();
这使用如上所述的按值变量绑定。两者都不会改变原来的指针。
$arr = $array = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // echoes 'apple'
如果不想丢失当前指针的位置,只需为数组创建一个别名。
有两个解决方案。
解决方案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]];
这是一个结合了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