Get the first element of an array

2018-12-31 14:30发布

I have an array:

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

I would like to get the first element of this array. Expected result: string apple

One requirement: it cannot be done with passing by reference, so array_shift is not a good solution.

How can I do this?

标签: php arrays
30条回答
像晚风撩人
2楼-- · 2018-12-31 15:11

A small change to what Sarfraz posted is:

$array = array(1, 2, 3, 4, 5);
$output = array_slice($array, 0, 1);
print_r ($output);
查看更多
余生请多指教
3楼-- · 2018-12-31 15:12

I like the "list" example, but "list" only works on the left-hand-side of an assignment. If we don't want to assign a variable, we would be forced to make up a temporary name, which at best pollutes our scope and at worst overwrites an existing value:

list($x) = some_array();
var_dump($x);

The above will overwrite any existing value of $x, and the $x variable will hang around as long as this scope is active (the end of this function/method, or forever if we're in the top-level). This can be worked around using call_user_func and an anonymous function, but it's clunky:

var_dump(call_user_func(function($arr) { list($x) = $arr; return $x; },
                        some_array()));

If we use anonymous functions like this, we can actually get away with reset and array_shift, even though they use pass-by-reference. This is because calling a function will bind its arguments, and these arguments can be passed by reference:

var_dump(call_user_func(function($arr) { return reset($arr); },
                        array_values(some_array())));

However, this is actually overkill, since call_user_func will perform this temporary assignment internally. This lets us treat pass-by-reference functions as if they were pass-by-value, without any warnings or errors:

var_dump(call_user_func('reset', array_values(some_array())));
查看更多
无色无味的生活
4楼-- · 2018-12-31 15:12

I don't like fiddling with the array's internal pointer, but it's also inefficient to build a second array with array_keys() or array_values(), so I usually define this:

function array_first(array $f) {
    foreach ($f as $v) {
        return $v;
    }
    throw new Exception('array was empty');
}
查看更多
残风、尘缘若梦
5楼-- · 2018-12-31 15:13

I would do echo current($array) .

查看更多
零度萤火
6楼-- · 2018-12-31 15:13

A kludgy way is:

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

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

print get_first($foo);
查看更多
看淡一切
7楼-- · 2018-12-31 15:14
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
foreach($arr as $first) break;
echo $first;

Output:

apple
查看更多
登录 后发表回答