Master PHP 7.3’s array_key_first(): Retrieve the First Array Key Effortlessly
This guide explains PHP 7.3’s new array_key_first() function, showing its syntax, return behavior, practical examples for fetching the first key and checking for empty arrays, and highlights a subtle caveat when null values are present.
PHP 7.3 introduced the array_key_first() function, which returns the first key of an array or null if the array is empty.
Syntax
array_key_first (array $array) : mixedDescription
The function accepts a single array argument and returns the value of its first key. If the array contains no elements, it returns null.
Example 1 – Basic Usage
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // outputs aExample 2 – Empty Array
$arr = [];
echo array_key_first($arr); // outputs nullUse Cases
1. Retrieve the first element’s key
Before PHP 7.3, developers often combined reset() to get the first value and key() to obtain its key. array_key_first() simplifies this to a single call.
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // outputs a2. Determine if an array is empty
Older code used empty() or count(). With array_key_first(), you can check for emptiness directly:
$arr = [];
if (array_key_first($arr) === null) {
echo '数组为空';
}Output:
数组为空Important Note
If an array contains an element whose value is null, using array_key_first() may lead to unexpected results, so extra caution is required.
Conclusion
The array_key_first() function provides a concise way to obtain the first key of an array and to check for an empty array in PHP 7.3+, but developers should be aware of the edge case when null values are present.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
