Using array_key_first() in PHP 7.3: Syntax, Examples, and Use Cases
Introduced in PHP 7.3, the array_key_first() function returns the first key of an array or null for an empty array, and this article explains its syntax, demonstrates usage with code examples, and discusses practical scenarios such as retrieving the first key and checking if an array is empty.
PHP 7.3 added the array_key_first() function, which returns the first key of an array or null when the array is empty.
Syntax
array_key_first (array $array) : mixedDescription
The function accepts an array and returns the value of its first key; if the array is empty it returns null .
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. Getting the first element's key
Before PHP 7.3 developers often used reset() together with key() to obtain the first key; array_key_first() simplifies this to a single call.
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // outputs a2. Checking if an array is empty
Instead of empty() or count() , array_key_first() can be used to test emptiness directly.
$arr = [];
if (array_key_first($arr) === null) {
echo '数组为空';
}Result:
数组为空Note
If the array contains an element whose value is null , using array_key_first() may lead to unexpected behavior.
Conclusion
The array_key_first() function is a convenient addition in PHP 7.3 for retrieving the first key of an array and for quickly checking whether an array is empty, but developers should be cautious when the array includes null values.
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.