可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
Original answer, but costly (O(n)):
array_shift(array_values($array));
In O(1):
array_pop(array_reverse($array));
Edited with suggestions from comments for other use cases etc...
If modifying (in the sense of resetting array pointers) of $array
is not a problem, you might use:
reset($array);
This should be theoretically more efficient, if a array \"copy\" is needed:
array_shift(array_slice($array, 0, 1));
With PHP 5.4+ (but might cause an index error if empty):
array_values($array)[0];
回答2:
As Mike pointed out (the easiest possible way):
$arr = array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' )
echo reset($arr); //echoes \"apple\"
If you want to get the key: (execute it after reset)
echo key($arr); //echoes \"4\"
From PHP\'s documentation:
mixed reset ( array &$array );
Description:
reset() rewinds array\'s internal pointer to the first element and returns the value of the first array element, or FALSE if the array is
empty.
回答3:
$first_value = reset($array); // First Element\'s Value
$first_key = key($array); // First Element\'s Key
Hope this helps. :)
回答4:
$arr = array( 9 => \'apple\', 7 => \'orange\', 13 => \'plum\' );
echo reset($arr); // echoes \'apple\'
If you don\'t want to lose the current pointer position, just create an alias for the array.
回答5:
current($array)
can get you first element of an array, according to PHP Manual
Every array has an internal pointer to its \"current\" element, which is initialized to the first element inserted into the array.
So it works until you have re-positioned array pointer, otherwise you ll have to reset the array.
回答6:
You can get Nth element with a language construct \"list\":
// 1st item
list($firstItem) = $yourArray;
// 1st item from an array that is returned from function
list($firstItem) = functionThatReturnsArray();
// 2nd item
list( , $secondItem) = $yourArray;
with array_keys function you can do the same for keys:
list($firstKey) = array_keys($yourArray);
list(, $secondKey) = array_keys($yourArray);
回答7:
PHP 5.4+:
array_values($array)[0];
回答8:
Suppose:
$array = array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' );
Just use:
$array[key($array)]
to get first element or
key($array)
to get first key.
Or you can unlink the first if you want to remove it.
回答9:
Some arrays don\'t work with functions like list
, reset
or current
. Maybe they\'re \"faux\" arrays - partially implementing ArrayIterator, for example.
If you want to pull the first value regardless of the array, you can short-circuit an iterator:
foreach($array_with_unknown_keys as $value) break;
Your value will then be available in $value
and the loop will break after the first iteration. This is more efficient than copying a potentially large array to a function like array_unshift(array_values($arr)).
You can grab the key this way too:
foreach($array_with_unknown_keys as $key=>$value) break;
If you\'re calling this from a function, simply return early:
function grab_first($arr) {
foreach($arr as $value) return $value;
}
回答10:
Simply do:
array_shift(array_slice($array,0,1));
回答11:
I would do echo current($array)
.
回答12:
$arr = array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' );
foreach($arr as $first) break;
echo $first;
Output:
apple
回答13:
From Laravel\'s helpers:
function head($array)
{
return reset($array);
}
The array being passed by value to the function, the reset() affects the internal pointer of a copy of the array, it doesn\'t touch the original array. (note it returns false
if the array is empty)
Usage example:
$data = [\'foo\', \'bar\', \'baz\'];
current($data); // foo
next($data); // bar
head($data); // foo
next($data); // baz
Also, here is an alternative. It\'s very marginally faster, but more interesting, it lets easily change the default value if the array is empty:
function head($array, $default = null)
{
foreach ($array as $item) {
return $item;
}
return $default;
}
回答14:
$array=array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' );
$firstValue = each($array)[1];
This is much more efficient than array_values()
because the each()
function does not copy the entire array.
For more info see http://www.php.net/manual/en/function.each.php
回答15:
$myArray = array (4 => \'apple\', 7 => \'orange\', 13 => \'plum\');
$arrayKeys = array_keys($myArray);
// the first element of your array is:
echo $myArray[$arrayKeys[0]];
回答16:
PHP 7.3 added two functions for getting the first and the last key of an array directly without modification of the original array and without creating any temporary objects:
- array_key_first
- array_key_last
Apart from being semantically meaningful, these functions don\'t even move the array pointer (as foreach
would do).
Having the keys, one can get the values by the keys directly.
Examples (all of them require PHP 7.3+)
Getting the first/last key and value:
$my_array = [\'IT\', \'rules\', \'the\', \'world\'];
$first_key = array_key_first($my_array);
$first_value = $my_array[$first_key];
$last_key = array_key_last($my_array);
$last_value = $my_array[$last_key];
Getting the first/last value as one-liners, assuming the array cannot be empty:
$first_value = $my_array[ array_key_first($my_array) ];
$last_value = $my_array[ array_key_last($my_array) ];
Getting the first/last value as one-liners, with defaults for empty arrays:
$first_value = empty($my_array) ? \'default\' : $my_array[ array_key_first($my_array) ];
$last_value = empty($my_array) ? \'default\' : $my_array[ array_key_last($my_array) ];
回答17:
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);
回答18:
Most of these work! BUT for a quick single line (low resource) call:
$array = array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' );
echo $array[key($array)];
// key($array) -> will return the first key (which is 4 in this example)
Although this works, and decently well, please also see my additional answer:
https://stackoverflow.com/a/48410351/1804013
回答19:
Get first element:
array_values($arr)[0]
Get last element
array_reverse($arr)[0]
回答20:
Keep this simple! Lots of correct answers here, but to minimize all the confusion. These two work and reduce a lot of overhead.
key($array)
= gets the first key of an array
current($array)
= gets the first value of an array
回答21:
I think using array_values would be your best bet here. You could return the value at index zero from the result of that function to get \'apple\'.
回答22:
This is a little late to the game, but I was presented with a problem where my array contained array elements as children inside it, and thus I couldn\'t just get a string representation of the first array element. By using PHP\'s current()
function, I managed this:
<?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...
?>
Thanks to all the current solutions helped me get to this answer, I hope this helps someone sometime!
回答23:
Use:
$first = array_slice($array, 0, 1);
$val= $first[0];
By default, array_slice
does not preserve keys, so we can safely use zero as the index.
回答24:
Two solutions for you.
Solution 1 - Just use the key. You have not said, that you can not use it. :)
<?php
// get 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. */\');
?>
Solution 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 an reset in
// just to make sure that the array pointer is at first element
// also reset return the first element
// reset($myArray);
// return first key
$firstKey = key($array);
assert(\'$firstKey === \"apple\" /* Expected result: string apple. */\');
?>
Solution 3 - array_keys()
echo $array[array_keys($array)[0]];
回答25:
This is not soo simple response in real world. Supost that we have this examples of possibles responses that you can find in some libraries.
$array1 = array();
$array2 = array(1,2,3,4);
$array3 = array(\'hello\'=>\'world\', \'foo\'=>\'bar\');
$array4 = null;
var_dump( \'reset1\', reset($array1) );
var_dump( \'reset2\', reset($array2) );
var_dump( \'reset3\', reset($array3) );
var_dump( \'reset4\', reset($array4) ); // warning
var_dump( \'array_shift1\', array_shift($array1) );
var_dump( \'array_shift2\', array_shift($array2) );
var_dump( \'array_shift3\', array_shift($array3) );
var_dump( \'array_shift4\', array_shift($array4) ); // warning
var_dump( \'each1\', each($array1) );
var_dump( \'each2\', each($array2) );
var_dump( \'each3\', each($array3) );
var_dump( \'each4\', each($array4) ); // warning
var_dump( \'array_values1\', array_values($array1)[0] ); // Notice
var_dump( \'array_values2\', array_values($array2)[0] );
var_dump( \'array_values3\', array_values($array3)[0] );
var_dump( \'array_values4\', array_values($array4)[0] ); // warning
var_dump( \'array_slice1\', array_slice($array1, 0, 1) );
var_dump( \'array_slice2\', array_slice($array2, 0, 1) );
var_dump( \'array_slice3\', array_slice($array3, 0, 1) );
var_dump( \'array_slice4\', array_slice($array4, 0, 1) ); // warning
list($elm) = $array1; //Notice
var_dump($elm);
list($elm) = $array2;
var_dump($elm);
list($elm) = $array3; // Notice
var_dump($elm);
list($elm) = $array4;
var_dump($elm);
Like you can see, we have several \'one line\' solutions that work well in some cases, but not in all.
In my opinion, you have should that handler only with arrays.
Now talking about performance, assuming that we have always array, like this:
$elm = empty($array)? null : ...($array);
...you would use without errors:
$array[count($array)-1] ;
array_shift
reset
array_values
array_slice
array_shift is more fast that reset, that is more fast that [count()-1] and this three are more fast that array_values and array_slice
回答26:
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())));
回答27:
Also worth bearing in mind the context in which you\'re doing this, as an exhaustive check can be expensive and not always necessary.
For example, this solution works fine for the situation in which I\'m using it (but obviously can\'t be relied on in all cases...)
/**
* 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));
}
回答28:
A small change to what Sarfraz posted is:
$array = array(1, 2, 3, 4, 5);
$output = array_slice($array, 0, 1);
print_r ($output);
回答29:
Old post but anyway... I imagine the author just was looking for a way to get the first element of array after getting it from some function (mysql_fetch_row for example) without generating a STRICT \"Only variables should be passed by reference\". If it so, almos all ways described here will get this message... and some of them uses a lot of additional memory duplicating an array (or some part of it). An easy way to avoid it is just assigning the value inline before calling any of those functions:
$first_item_of_array = current($tmp_arr = mysql_fetch_row(...));
// or
$first_item_of_array = reset($tmp_arr = func_get_my_huge_array());
This way you don\'t get the STRICT message on screen neither in logs and you don\'t create any additional arrays. It works with both indexed AND associative arrays
回答30:
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\');
}