我有一个数组:

阵列(4 = > '苹果',7 = >“橙色”,13 = >“李子”)

我想要得到这个数组的第一个元素。预期结果:串苹果

一个要求:它不能通过引用传递来完成,所以array_shift不是一个好的解决方案。

我该怎么做呢?


当前回答

原来的答案,但代价高昂(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];

其他回答

$myArray = array (4 => 'apple', 7 => 'orange', 13 => 'plum');
$arrayKeys = array_keys($myArray);

// The first element of your array is:
echo $myArray[$arrayKeys[0]];

我输入echo current($array)

这有点晚了,但我遇到了一个问题,我的数组包含数组元素作为其子元素,因此我不能获得第一个数组元素的字符串表示形式。通过使用PHP的current()函数,我管理了这个:

<?php
    $original = array(4 => array('one', 'two'), 7 => array('three', 'four'));
    reset($original);  // to reset the internal array pointer...
    $first_element = current($original);  // get the current element...
?>

感谢所有当前的解决方案帮助我得到这个答案,我希望这能帮助到别人!

同样值得记住的是您执行此操作的上下文,因为详尽的检查可能是昂贵的,而且并不总是必要的。

例如,这个解决方案在我使用它的情况下工作得很好(但显然不能在所有情况下都依赖它……)

 /**
 * 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));
}

保持简单!这里有很多正确答案,但为了尽量减少所有的混乱,这两个方法有效,并减少了大量的开销:

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));