Understanding PHP 7.3 array_key_first() Function: Syntax, Usage, and Examples
PHP 7.3 introduces the array_key_first() function, which returns the first key of an array or null if empty; this article explains its syntax, provides code examples for retrieving the first key and checking for empty arrays, and highlights usage considerations and potential pitfalls.
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 argument and returns the value of its first key; if the array is empty it returns null.
Examples
Example 1:
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // 输出aExample 2:
$arr = [];
echo array_key_first($arr); // 输出nullUse Cases
1. Retrieve the first element's key
Before PHP 7.3 developers often used reset() to get the first value and key() to get its key; array_key_first() simplifies this process.
Example:
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // 输出a2. Determine if an array is empty
Instead of empty() or count(), array_key_first() can be used to check emptiness more directly.
Example:
$arr = [];
if (array_key_first($arr) === null) {
echo '数组为空';
}Result:
数组为空Summary
The array_key_first() function, introduced in PHP 7.3, provides a convenient way to obtain the first key of an array and can also be used to test whether an array is empty; however, developers should be cautious when the array contains elements with null values.
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.
