PHP - Using each() function to access array element

Introduction

PHP function each() returns the current element of the array, then advances the pointer to the next element.

each() returns a four-element array rather than a value.

This array contains both the key of the current element, as well as its value.

If an element could not be retrieved - because the pointer has reached the end of the array, or because the array is empty -each() returns false.

This makes it easy to tell if each() has retrieved an element with the value of false - in which case it returns the four-element array - or if it couldn't retrieve an element at all, in which case it returns false.

The four-element array that each() returns:

Element Index Element Value
0 The current element's key
"key"The current element's key
1 The current element's value
"value" The current element's value

You can use an index of either 0 or "key" to access the current element's key, or an index of 1 or "value" to access its value.

For example:

Demo

<?php

         $myBook = array("title"=> "Java",
                        "author"=> "John A",
                        "pubYear"=>  2018);

         $element = each($myBook);/*w  w  w . j  a  v a 2s . co  m*/
         echo"Key:". $element[0]."\n";
         echo"Value:". $element[1]."\n";
         echo"Key:". $element["key"]."\n";
         echo"Value:". $element["value"]."\n";
?>

Result

Here's how to use each() to retrieve an array element with a value of false :

$myArray = array(false);
$element = each($myArray);
$key = $element["key"]; // $key now equals 0
$val = $element["value"]; // $val now equals false

Because each() both returns the current array element and advances the array pointer, it's easy to use it in a while loop to move through all the elements of an array.

The following example works through the $myBook array, returning each element's key and value as it goes.

Demo

<?php
          $myBook = array("title"=> "Java",
                          "author"=> "John A",
                          "pubYear"=>  2018);

          while ($element = each($myBook)) {
            echo"$element[0]";
            echo" ";
            echo"$element[1]";
            echo"\n";
          }//from  w  w  w  . j av a2s  . co m

?>

Result

Related Topic