PHP array_key_first() function
The array_key_first () function in PHP gets the first key of an array if the specified array is not empty.
Syntax
array_key_first(array;$array)
Parameter
array(required)- This parameter signifies the input array.
Return
This function returns the first key of the specified array if the array is not empty else it returns NULL.
Example 1
1, 'second' => 2, 'third' => 3,'fourth' => 4];
echo("Array : \n");
var_export($array);
//will return the first key for $array
$firstKey = array_key_first($array);
//printing the returned value
echo("\nThe first key is ");
var_dump($firstKey);
?>
Output
Array: array ( 'first' => 1, 'second' => 2, 'third' => 3, 'fourth' => 4, ) The first key is string(5) "first"
Example 2
96, 'Harshit' => 94, 'Sapna' => 93,'Chandhan' => 92];
echo("Student Array : \n");
var_export($student_array);
//will return the first key for $array
$firstKey = array_key_first($student_array);
//printing the returned value
echo("\nThe topper of the class is ");
var_dump($firstKey);
?>
Output
Student Array: array ( 'Reema' => 96, 'Harshit' => 94, 'Sapna' => 93, 'Chandhan' => 92, ) The topper of the class is string(5) "Reema"
Example 3
Output
Array: 'The first key of the array is 0'
Example 4
'Reema',4 => 'Harshit',3 =>'Sapna'];
echo("Student Array : \n");
var_export($array);
//will return the last key for $array
$firstKey = array_key_first($array);
//printing the returned value
echo("\nThe first element is ");
var_export($firstKey);
// sorting the keys of the arrays in ascending order
ksort($array);
echo("\nNew Array: ");
var_export($array);
echo("\nThe first element is ".array_key_first($array));
?>
Output
Student Array : array ( 9 => 'Reema', 4 => 'Harshit', 3 => 'Sapna', ) The first element is 9 New Array: array ( 3 => 'Sapna', 4 => 'Harshit', 9 => 'Reema', ) The first element is 3
