I have an array:
array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' )
I would like to get the first element of this array. Expect
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:
"There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys(), but that may be rather inefficient. It is also possible to use reset() and key(), but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill:"
<?php
if (!function_exists('array_key_first')) {
function array_key_first($arr) {
foreach($arr as $key => $unused) {
return $key;
}
return NULL;
}
}
if (!function_exists('array_key_last')) {
function array_key_last($arr) {
return array_key_first(array_reverse($arr, true));
}
}
?>
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
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.
$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
Get first element:
array_values($arr)[0]
Get last element
array_reverse($arr)[0]
I imagine the author just was looking for a way to get the first element of an 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, almost all the 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, nor in logs, and you don't create any additional arrays. It works with both indexed AND associative arrays.