array_key_first(): to get the first key of an array

key = array_key_first ($input_array);
ParameterDESCRIPTION
$input_arrayRequired : Input array for which first key is to be returned.
arrays_key_first() function returns the first key of the array. If the array is empty then NULL is returned.
PHP 7.3.0 : Supported by PHP 7.3.0 and above

Example 1

$input=array(1,2,3,4,5);
echo array_key_first($input);
Output is here
0

Example 2

$input=array('One' =>'First','Two'=>'Second','Three'=>'Third','Fourth');
echo var_dump(array_key_first($input));
The output is here
string(3) "One"

Getting first key using array_keys()

$input=array('One' =>'First','Two'=>'Second','Three'=>'Third','Fourth');
echo (array_keys($input)[0]);
Output
One

Example 2: Using array_key_first() with Indexed Arrays

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

Example 3: Handling Empty Arrays

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.";
}

Use Case: Efficient Retrieval of First Element in Large Arrays

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 

Example 4: Using array_key_first() in Combination with array_filter()

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

read more on array_keys()


Returns the Last Key
Array REFERENCE
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com











    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer