key = array_key_first ($input_array);
Parameter | DESCRIPTION |
---|---|
$input_array | Required : Input array for which first key is to be returned. |
$input=array(1,2,3,4,5);
echo array_key_first($input);
Output is here
0
$input=array('One' =>'First','Two'=>'Second','Three'=>'Third','Fourth');
echo var_dump(array_key_first($input));
The output is here
string(3) "One"
$input=array('One' =>'First','Two'=>'Second','Three'=>'Third','Fourth');
echo (array_keys($input)[0]);
Output
One
Although array_key_first() is often used with associative arrays, it works with indexed arrays as well:
$indexed_array = [10, 20, 30];
echo array_key_first($indexed_array); // Outputs: 0
If the array is empty, array_key_first() will return NULL. It's useful to check for this condition:
$empty_array = [];
if (is_null(array_key_first($empty_array))) {
echo "The array is empty.";
}
In large arrays, using array_key_first() is more efficient than resetting the internal pointer with *reset()*. This avoids modifying the array's internal state:
$large_array = range(1, 1000000);
$first_key = array_key_first($large_array); // Efficient
echo $large_array[$first_key]; // Output 1
We can use array_key_first() to quickly retrieve the first key from a filtered array:
$arr = [1, 2, 3, 4, 5];
$filtered = array_filter($arr, function($val) {
return $val > 3;
});
$first_key = array_key_first($filtered);
echo "First key after filtering: " . $first_key;
Output
First key after filtering: 3