The Wayback Machine - https://web.archive.org/web/20250114174205/https://www.geeksforgeeks.org/php-each-function/
Open In App

PHP each() Function

Last Updated : 20 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The each() function is an inbuilt function in PHP and is used to get the current element key-value pair of the given array to which the internal pointer is currently pointing. After returning the key and value of the current element the internal pointer is incremented by one in the array.

Note: You can use reset() function if you want to traverse the array again using each().

Syntax:

each($array)

Parameter: This function accepts a single parameter $array which is the input array in which we want to find the current key-value pair to which the internal pointer is currently pointing.

Return Value: This function returns the key-value pair of the current element of the input array $array. The key-value pair is returned in the form of a new array containing four elements. The first two elements with keys(1 and Value) are for the current element’s value, and next two elements with keys (0 and Key) are for the current element’s key. If the input array is empty or if the internal pointer has reached the end of the array then this function returns FALSE.

Examples:

Input : each(array('Ram', 'Shita', 'Geeta'))
Output :
Array
(
    [1] => Ram
    [value] => Ram
    [0] => 0
    [key] => 0
)
Explanation: Here input array contain many elements
but ram is the current element so the output contains
its key and value pair. 

Below programs illustrate the each() function in PHP:

Program 1:




<?php
  
$arr = array('maya', 'Sham', 'Geet');
  
print_r (each($arr));
  
?>


Output:

Array
(
    [1] => maya
    [value] => maya
    [0] => 0
    [key] => 0
)

Program 2:




<?php
  
$arr = array('a' => 'anny', 'b' => 'bunny', 
                           'c' => 'chinky');
  
reset($arr);
  
while (list($key, $val) = each($arr))
  {
      echo "$key => $val \n";
  }
  
?>


Output:

a => anny 
b => bunny 
c => chinky 

Reference: http://php.net/manual/en/function.each.php


Become a Full-Stack Developer and also get 90% fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.

After successfully processing refunds worth over INR 5 Cr, GeeksforGeeks is back with the Three 90 challenge and this is your chance to upskill and get 90% refund. What more motivation do you need? Start the challenge right away!


Article Tags :

Similar Reads

three90RightbarBannerImg