我有一个数组:

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

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

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

我该怎么做呢?


当前回答

这有点晚了,但我遇到了一个问题,我的数组包含数组元素作为其子元素,因此我不能获得第一个数组元素的字符串表示形式。通过使用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...
?>

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

其他回答

这有点晚了,但我遇到了一个问题,我的数组包含数组元素作为其子元素,因此我不能获得第一个数组元素的字符串表示形式。通过使用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...
?>

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

我认为使用array_values是最好的选择。你可以从函数的结果中返回下标0处的值,得到'apple'。

这是一个结合了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

PHP 5.4 +:

array_values($array)[0];

一种简单的方法是:

$foo = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );

function get_first ($foo) {
    foreach ($foo as $k=>$v){
        return $v;
    }
}

print get_first($foo);