我有一个数组:
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
我想要得到这个数组的第一个元素。预期结果:串苹果
一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。
我该怎么做呢?
我有一个数组:
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
我想要得到这个数组的第一个元素。预期结果:串苹果
一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。
我该怎么做呢?
当前回答
PHP 5.4 +:
array_values($array)[0];
其他回答
大部分都有用!但是对于一个快速的单线(低资源)呼叫:
$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
有两个解决方案。
解决方案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]];
原来的答案,但代价高昂(O(n)):
array_shift(array_values($array));
在O (1):
array_pop(array_reverse($array));
其他用例,等等……
如果修改(在重置数组指针的意义上)$array不是一个问题,你可以使用:
reset($array);
如果需要数组“copy”,理论上这应该更有效:
array_shift(array_slice($array, 0, 1));
使用PHP 5.4+(但如果为空可能会导致索引错误):
array_values($array)[0];
我认为使用array_values是最好的选择。你可以从函数的结果中返回下标0处的值,得到'apple'。
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
foreach($arr as $first) break;
echo $first;
输出:
apple