Get the first value in an associative PHP array
May 8, 2022 ‐ 1 min read
Not only numerically indexed arrays but also associative arrays are ordered in PHP. Meaning, that you can be certain that the keys in an associative array will maintain their respective order.
This allows you not only reliably access the first value in an array, but also the first key. To do so you can use the
array_key_first() function that was introduced in PHP 7.3, this you may use to access the first value in an associative.
To get the first value in a multidimensional array you first get the first key, next you use this key to access the first value.
<?php $data = [ '2022-02-14' => 'Monday', '2022-02-15' => 'Tuesday', '2022-02-16' => 'Wednesday', ]; $first = $data[array_key_first($data)]; echo $first; // => Monday
As with about everything you have multiple options. You could for example first grab only the values in the array, and take the first element from there as follows:
<?php $data = [ '2022-02-14' => 'Monday', '2022-02-15' => 'Tuesday', '2022-02-16' => 'Wednesday', ]; echo array_values($data); // => Monday
This one-line approach might be a nice alternative when it comes to code readability. It is somewhat more expansive in terms of performance however.