The key() function simply returns the key of the array element that's
currently being pointed to by the internal pointer. It does not move
the pointer in any way. If the internal pointer points beyond the end
of the elements list or the array is empty, key() returns NULL.
Example:
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
Expanding on Ram Dane's answer, the key function is an alternative way to get the key of the current index of the array. You can create the following function,
If it is the first element, i.e. $array[0], you can try:
echo key($array);
If it is the second element, i.e. $array[1], you can try:
next($array);
echo key($array);
I think this method is should be used when required element is the first, second or at most third element of the array. For other cases, loops should be used otherwise code readability decreases.