Problem:
You want to know the key of the first element of an array.
Solution:
To get the key of the first element, first we’ll set the internal pointer of the array to the first element, then, we’ll fetch the key of that selected pointed element. See the example below-
<?php $months = array( 2 => "January", 3 => "February", 4 => "March", 5 => "April", 6 => "May", 7 => "June", 8 => "July", 9 => "August", 10 => "September", 11 => "October", 12 => "November", 13 => "December"); reset($months); $first_key = key($months); echo $first_key; ?>
[wpdm_file id=77]
Output:
2
How it Works:
Line 15 | The reset function puts the internal pointer of the $month[] array to its first element which is “January” here. |
Line 16 | The key() function returns the key of the array element which is currently being pointed by the array pointer. Here, the currently pointed array element is “January” and its key is 2. So the function returns 2. |
Line 17 | Prints the key which is 2. |
Note: You can also get first array key of an associative array in the method.