我有一个数组:

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

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

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

我该怎么做呢?


当前回答

一种简单的方法是:

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

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

print get_first($foo);

其他回答

一些数组不能与list、reset或current等函数一起使用。也许它们是“人造”数组——例如,部分实现了ArrayIterator。

如果你想拉出第一个值而不考虑数组,你可以短路迭代器:

foreach($array_with_unknown_keys as $value) break;

然后你的值将在$value中可用,循环将在第一次迭代后中断。这比将一个潜在的大数组复制到array_unshift(array_values($arr))这样的函数更有效。

你也可以用这种方式获取钥匙:

foreach($array_with_unknown_keys as $key=>$value) break;

如果你从函数中调用这个函数,只要提前返回:

function grab_first($arr) {
    foreach($arr as $value) return $value;
}

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

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

 /**
 * 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));
}
<?php
    $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
    echo array_values($arr)[0]; // Outputs: Apple
?>

其他的例子:

<?php
    $arr = array(3 => "Apple", 5 => "Ball", 11 => "Cat");
    echo current($arr); // Outputs: Apple
    echo reset($arr); // Outputs: Apple
    echo next($arr); // Outputs: Ball
    echo current($arr); // Outputs: Ball
    echo reset($arr); // Outputs: Apple
?>
$arr = $array = array( 9 => 'apple', 7 => 'orange', 13 => 'plum' );
echo reset($arr); // echoes 'apple'

如果不想丢失当前指针的位置,只需为数组创建一个别名。

一种简单的方法是:

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

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

print get_first($foo);