我有一个数组:
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
我想要得到这个数组的第一个元素。预期结果:串苹果
一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。
我该怎么做呢?
我有一个数组:
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
我想要得到这个数组的第一个元素。预期结果:串苹果
一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。
我该怎么做呢?
当前回答
这是一个结合了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
其他回答
你可以用一个语言结构"list"得到第n个元素:
// First item
list($firstItem) = $yourArray;
// First item from an array that is returned from a function
list($firstItem) = functionThatReturnsArray();
// Second item
list( , $secondItem) = $yourArray;
使用array_keys函数,你可以对键做同样的事情:
list($firstKey) = array_keys($yourArray);
list(, $secondKey) = array_keys($yourArray);
这里有太多的答案,选择的答案将适用于大多数情况。
在我的例子中,我有一个2D数组,array_values出于某种奇怪的原因删除了内部数组上的键。所以我的结论是:
$keys = array_keys($myArray); // Fetches all the keys
$firstElement = $myArray[$keys[0]]; // Get the first element using first key
同样值得记住的是您执行此操作的上下文,因为详尽的检查可能是昂贵的,而且并不总是必要的。
例如,这个解决方案在我使用它的情况下工作得很好(但显然不能在所有情况下都依赖它……)
/**
* A quick and dirty way to determine whether the passed in array is associative or not, assuming that either:<br/>
* <br/>
* 1) All the keys are strings - i.e. associative<br/>
* or<br/>
* 2) All the keys are numeric - i.e. not associative<br/>
*
* @param array $objects
* @return boolean
*/
private function isAssociativeArray(array $objects)
{
// This isn't true in the general case, but it's a close enough (and quick) approximation for the context in
// which we're using it.
reset($objects);
return count($objects) > 0 && is_string(key($objects));
}
原来的答案,但代价高昂(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];
一行闭行,复制,重置:
<?php
$fruits = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
echo (function() use ($fruits) { return reset($fruits); })();
输出:
apple
或者更短的短箭头函数:
echo (fn() => reset($fruits))();
这使用如上所述的按值变量绑定。两者都不会改变原来的指针。