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:
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.
$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];
$first_value = $my_array[ array_key_first($my_array) ];
$last_value = $my_array[ array_key_last($my_array) ];
$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) ];
PHP 5.4+:
array_values($array)[0];
$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key
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, and 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;
}
For the record, here is another answer of mine, for the array's last element.
Keep this simple! There are 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
EDIT:
Regarding the comments below. The following example will output: string(13) "PHP code test"
$array = array
(
'1' => 'PHP code test',
'foo' => 'bar', 5 , 5 => 89009,
'case' => 'Random Stuff: '.rand(100,999),
'PHP Version' => phpversion(),
0 => 'ending text here'
);
var_dump(current($array));
$arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
foreach($arr as $first) break;
echo $first;
Output:
apple