我有一个数组:
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
我想要得到这个数组的第一个元素。预期结果:串苹果
一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。
我该怎么做呢?
我有一个数组:
阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)
我想要得到这个数组的第一个元素。预期结果:串苹果
一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。
我该怎么做呢?
当前回答
保持简单!这里有很多正确答案,但为了尽量减少所有的混乱,这两个方法有效,并减少了大量的开销:
Key ($array)获取数组的第一个键 Current ($array)获取数组的第一个值
编辑: 关于下面的评论。以下示例将输出string(13)“PHP代码测试”
$array = array
(
'1' => 'PHP code test',
'foo' => 'bar', 5 , 5 => 89009,
'case' => 'Random Stuff: '.rand(100,999),
'PHP Version' => phpversion(),
0 => 'ending text here'
);
var_dump(current($array));
其他回答
你可以通过下面的代码获取第一个元素:
$array_key_set = array_keys($array);
$first_element = $array[$array_key_set[0]];
或者使用:
$i=0;
foreach($array as $arr)
{
if($i==0)
{
$first_element=$arr;
break;
}
$i++;
}
echo $first_element;
保持简单!这里有很多正确答案,但为了尽量减少所有的混乱,这两个方法有效,并减少了大量的开销:
Key ($array)获取数组的第一个键 Current ($array)获取数组的第一个值
编辑: 关于下面的评论。以下示例将输出string(13)“PHP代码测试”
$array = array
(
'1' => 'PHP code test',
'foo' => 'bar', 5 , 5 => 89009,
'case' => 'Random Stuff: '.rand(100,999),
'PHP Version' => phpversion(),
0 => 'ending text here'
);
var_dump(current($array));
有两个解决方案。
解决方案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]];
没有人建议使用ArrayIterator类:
$array = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
$first_element = (new ArrayIterator($array))->current();
echo $first_element; //'apple'
绕过OP的参照规定。
同样值得记住的是您执行此操作的上下文,因为详尽的检查可能是昂贵的,而且并不总是必要的。
例如,这个解决方案在我使用它的情况下工作得很好(但显然不能在所有情况下都依赖它……)
/**
* 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));
}