Home > Article > Backend Development > PHP function exploration-array_key_first()
PHP function exploration-array_key_first()
In PHP 7.3, an official new array function-array_key_first() has been added. This function returns the first key in the array. In this article, we will delve into the usage and scenarios of this function.
Syntax
array_key_first (array $array) : mixed
Description
array_key_first() function receives an array parameter and returns the first one in the array The value of a key name, or null if the array is empty.
Example
Example 1:
$arr = ['a' => 1, 'b' => 2, 'c' => 3] ;
echo array_key_first($arr); // Output a
Example 2:
$arr = [];
echo array_key_first($arr) ; // Output null
Usage scenarios
In some cases, we need to get a The key name of the first element in the array. Before PHP 7.3, we could use the reset() function to get the value of the first element, and then use the key() function to get the key value of the element. However, using array_key_first() is simpler than using the reset() and key() functions.
Example:
$arr = ['a' => 1, 'b' => 2, 'c' => 3];
echo array_key_first($arr); // Output a
In some cases, we need to judge whether an array is empty. Before PHP 7.3, we could use the empty() function or count() function to make judgments. However, this function can be implemented more simply using the array_key_first() function.
Example:
$arr = [];
if (array_key_first($arr) === null) {
echo 'The array is empty ';
}
Run result:
The array is empty
It should be noted that if there is an element with a null value in the array, use There may be an error in the array_key_first() function.
Summary
array_key_first() function is a new array function in PHP 7.3. It is very convenient to use when getting the value of the first key name in the array. It can also be used for judgment. Whether the array is empty. When using it, you need to be careful when using it when there are elements with null values in the array.
The above is the detailed content of PHP function exploration-array_key_first(). For more information, please follow other related articles on the PHP Chinese website!