Understanding PHP's array_key_first() Function: Syntax, Usage, and Examples
This article introduces PHP 7.3's new array_key_first() function, explains its syntax, demonstrates usage with examples for retrieving the first key and checking for empty arrays, discusses practical scenarios, and highlights precautions when arrays contain null values.
In PHP 7.3, a new array function array_key_first() was introduced, which returns the first key of an array.
Syntax
array_key_first (array $array) : mixedDescription
The function accepts an array and returns the value of its first key, or null if 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. Retrieve the first element's key name
Before PHP 7.3, developers often used reset() to get the first value and key() to get its key. Using array_key_first() is simpler.
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // outputs a2. Determine whether an array is empty
Previously empty() or count() were used. array_key_first() can check emptiness more directly.
$arr = [];
if (array_key_first($arr) === null) {
echo 'Array is empty';
}Result:
Array is emptyNote that if an array contains an element with a null value, array_key_first() may produce unexpected results.
Conclusion
The array_key_first() function, added in PHP 7.3, provides a convenient way to obtain the first key of an array and can also be used to check if 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.