Understanding PHP 7.3 array_key_first(): Syntax, Usage, and Examples
PHP 7.3 introduced the array_key_first() function, which returns the first key of an array or null if empty; this article explains its syntax, demonstrates usage with examples, compares it to older approaches, and outlines scenarios such as retrieving the first key and checking for empty arrays.
In PHP 7.3, the official release added a new array function— array_key_first() . This function can return the first key name of an array; if the array is empty it returns null.
Syntax
array_key_first (array $array) : mixedDescription
The array_key_first() function accepts an array argument and returns the value of its first key, or null when the array is empty.
Example 1
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // outputs aExample 2
$arr = [];
echo array_key_first($arr); // outputs nullUse Cases
1. Get the first element's key name
Previously, developers used reset() to get the first element's value and key() to obtain its key. The array_key_first() function simplifies this process.
Example:
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // outputs a2. Determine if an array is empty
Earlier, empty() or count() were used to check emptiness. Using array_key_first() provides a more straightforward way.
Example:
$arr = [];
if (array_key_first($arr) === null) {
echo 'Array is empty';
}Output:
Array is emptyNote that if the array contains elements with a null value, array_key_first() may behave unexpectedly.
Conclusion
The array_key_first() function, introduced in PHP 7.3, is convenient for retrieving the first key of an array and can also be used to check if an array is empty, but caution is required when the array includes null values.
PHP Practical Development Rapid Introduction
Scan the QR code to receive free learning materials
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.