each

(PHP 4, PHP 5, PHP 7)

each배열에서 현재 키와 값 쌍을 반환하고 배열 커서를 전진

설명

array each ( array &$array )

배열에서 현재 키와 값 쌍을 반환하고 배열 커서를 전진합니다.

each()를 실행한 후에, 배열 커서는 배열의 다음 원소를 가르키거나, 배열의 끝이라면 마지막 원소 뒤를 가르킵니다. each를 사용해서 배열을 다시 따라가려면 reset()해야 합니다.

인수

array

입력 배열.

반환값

array 배열에서 현재의 키와 값 쌍을 반환하고 배열 커서를 전진시킨다. 이 키/값 쌍은 4개 원소를 갖는 배열을 반환한다. 0, 1, key, value 이다. 원소 0key는 배열 원소의 키 이름을 포함하고, 1value는 데이터를 포함한다.

배열의 내부 포인터가 배열의 끝을 벗어나면, each()FALSE를 반환한다.

예제

Example #1 each() 예제

<?php
$foo 
= array("bob""fred""jussi""jouni""egon""marliese");
$bar each($foo);
print_r($bar);
?>

$bar는 현재 다음과 같은 key/value 쌍을 포함한다:

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

<?php
$foo 
= array("Robert" => "Bob""Seppo" => "Sepi");
$bar each($foo);
print_r($bar);
?>

$bar는 현재 다음과 같은 key/value 쌍을 포함한다:

Array
(
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
)

each()는 배열을 따라가기 위해 일반적으로 list()와 같이 사용한다. 여기에 예제가 있습니다:

Example #2 each()로 배열 따라가기

<?php
$fruit 
= array('a' => 'apple''b' => 'banana''c' => 'cranberry');

reset($fruit);
while (list(
$key$val) = each($fruit)) {
    echo 
"$key => $val\n";
}
?>

위 예제의 출력:

a => apple
b => banana
c => cranberry

Caution

배열을 다른 변수로 지정하는 것은 원래의 배열 포인터를 초기화 하는것이기 때문에, 위 예제코드는 루프안에서 $fruit를 다른 변수로 지정하게 되면 무한 루프를 유발할수 있다.

Warning

each()는 객체를 받아들이지만, 기대하지 않은 결과를 반환할 수 있습니다. 그러므로 객체 프로퍼티를 each()로 반복하는 일은 권장하지 않습니다.

참고

  • key() - 배열에서 키를 가져옵니다
  • list() - 배열처럼 변수에 할당
  • current() - 배열의 현재 원소를 반환
  • reset() - 배열의 내부 포인터를 첫 원소로 설정
  • next() - 배열의 내부 배열 포인터를 전진
  • prev() - 내부 배열 포인터를 후진
  • foreach
  • 객체 반복

add a note add a note

User Contributed Notes 21 notes

up
36
wolfeym38 at yahoo dot com
12 years ago
Regarding speed of foreach vs while(list) =each
I wrote a benchmark script and the results are that clearly foreach is faster. MUCH faster. Even with huge arrays (especially with huge arrays). I tested with sizes 100,000. 1,000,000 and 10,000,000. To do the test with 10 million i had to set my memory limit real high, it was close to 1gb by the time it actually worked. Anyways,

<?php
function getDiff($start, $end) {
   
$s = explode(' ', $start);
   
$stot = $s[1] + $s[0];
   
$e = explode(' ', $end);
   
$etot = $e[1] + $e[0];
    return
$etot - $stot;
}

$lim=10000000;
$arr = array();
for (
$i=0; $i<$lim; $i++) {
   
$arr[$i] = $i/2;
}

$start = microtime();
foreach (
$arr as $key=>$val);

$end = microtime();
echo
"time for foreach = " . getDiff($start, $end) . ".\n";

reset($arr);
$start = microtime();
while (list(
$key, $val) = each($arr));
$end = microtime();
echo
"time list each = " . getDiff($start, $end) . ".\n";
?>

here are some of my results: with 1,000,000
time for foreach = 0.0244591236115.
time list each = 0.158002853394.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0245339870453.
time list each = 0.154260158539.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0269000530243.
time list each = 0.157305955887.

then with 10,000,000:
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 1.96586894989.
time list each = 14.1371650696.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.02504014969.
time list each = 13.7696218491.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.0246758461.
time list each = 13.8425710201.

by the way, these results are with php 5.2 i believe, and a linux machine with 3gb of ram and 2.8ghz dual core pentium
up
2
Anonymous
1 year ago
An odd function to deprecate. If you're keeping track of an array pointer in a collection outside a foreach loop you don't care about performance and the utility of this function is core.

Instead you must call two functions: current() and then next() to replicate its behaviour.
up
6
james at gogo dot co dot nz
14 years ago
It's worth noting that references to an array don't have thier own array pointer, and taking a reference to an array doesn't reset it's array pointer, so this works as you would expect it would by eaching the first three items of the array, rather than the first item 3 times.

<?php
  $x
= array(1,2,3);

 
print_r(each($x));
  echo
"\n";
 
 
$y =& $x;
 
print_r(each($y));
  echo
"\n";
 
 
$z =& $y;
 
print_r(each($z));
  echo
"\n";
?>
up
10
sjoerd-php at linuxonly dot nl
13 years ago
Use foreach instead of while, list and each. Foreach is:
- easier to read
- faster
- not influenced by the array pointer, so it does not need reset().

It works like this:
<?php
$arr
= array('foo', 'bar');
foreach (
$arr as $value) {
    echo
"The value is $value.";
}

$arr = array('key' => 'value', 'foo' => 'bar');
foreach (
$arr as $key => $value) {
    echo
"Key: $key, value: $value";
}
?>
up
3
Sopinon
14 years ago
If you want to display the hole structure (tree) of your array, then you can use this recursive solution.

<?PHP
$tree
= "";
array_tree($your_array);
echo
$tree;

// Recursive Function
function array_tree($array, $index=0){
    global
$tree;
   
$space="";
    for (
$i=0;$i<$index;$i++){
       
$space .= "     ";
    }
    if(
gettype($array)=="array"){
       
$index++;
        while (list (
$x, $tmp) = each ($array)){
           
$tree .= $space."$x => $tmp\n";
           
array_tree($tmp, $index);
        }
    }
}
?>
up
2
amby2 at izh dot com
13 years ago
I've found a compact way to cycle through an associative array using for statement (not while, as it has been done in the most of examples below):

<?php

for (reset($array); list($key) = each($array);) {
  echo
$key;
  echo
$array[$key];
}

?>

or

<?php

for (reset($array); list($key, $value) = each($array);) {
  echo
$key;
  echo
$value;
  echo
$array[$key];
}

?>

You hardly forget to add reset($array) code line using such construction.
up
2
matthew at mhalls dot net
13 years ago
To panania at 3ringwebs dot com:

If you know for certain that you are only receiving one row, the while becomes redundant. To shorten your code:

$strSQL = "SELECT * FROM table WHERE id=1";
$RecordsetSelect = $db->runQuery ($strSQL);
list($key, $val) = mysql_fetch_row($RecordsetSelect);
echo "$key => $val\n";
mysql_free_result($RecordsetSelect);

With only one row being returned this is more elegant a solution, but just being nit-picky in essence. It also shows another quick way of using list.
up
1
massimo dot modica at tin dot it
9 years ago
If you forget to reset the array before each(), the same code may give different results with different php versions.

<?php

$a
= array(1,2,3);

foreach (
$a AS $k => $v) $a[$k] = 2*$v;

while(list(
$k2, $v2) = each($a)) { echo($v2."\n"); }

?>

In PHP 5.2.0:

2
4
6

In PHP 5.2.6:

4
6
up
1
michael k (name der redaktion bekannt.)
12 years ago
If you want to iterate over a two-dimensional, sparse array, and want to  first display every first element, then every second and so on, you can use this code:

$fruits = array ( "fruits"  => array ( "a" => "orange",
                                      "b" => "banana",
                                      "c" => "apple"
                                    ),
                 "numbers" => array ( 1,
                                      2,
                                      3,
                                      4,
                                      5,
                                      6
                                    ),
                 "holes"   => array (      "first",
                                      5 => "second",
                                           "third",
                                     10 => "fourth",
                                    )
               );

$done = False;
while ($done == False) {       
       $done = True;

       // Important: &$val has to be a reference (use the &),
       // if you don't, the internal counter of $val will be
       // re-initialized each time and you loop over the first elements
       // for eternity.

       foreach($fruits as $key => &$val) {

               if (list($inner_key, $inner_val) = each(&$val)) {
                       $done = False;
                       echo "$key : : $inner_key => $inner_val  <br>  \n";
               }

       }
}

NOTE: this is just a quick hack, if you know a better way, post it!
up
1
Gillis at dancrea dot com
17 years ago
I wrote a short and pretty simple script to search through associative arrays for some value in the values, heres a simplifyed example of it:

<?php

$foo
['bob'] = "bob is ugly";
$foo['bill'] = "bill is rich";
$foo['barbie'] = "barbie is cute";
$search = "rich";

echo
"searching the array foo for $search:<br>";
reset ($foo);
while (list (
$key, $val) = each ($foo)) {
if (
preg_match ("/$search/i", $val)) {
    print
"A match was found in $key.<br />";
} else {
    print
"A match was not found in $key.<br />";
}
}

?>

will output:
Searching the array foo for rich:
A match was not found in bob
A match was found in bill
A match was not found in barbie
up
0
phpcoder at gmail dot com
2 months ago
each was deprecated because it exposed too much of the internal implementation details, blocking language development. ("We can't do X because it would break each().")

https://wiki.php.net/rfc/deprecations_php_7_2#each

If you want an array pointer, maintain it yourself. Probably a good idea anyway, because then it's visible in the code.
up
0
13975001197 at 163 dot com
1 year ago
In PHP 7.2 we can use foreach() to replace each(), such as:

foreach($array as $key => $value) {
    //do something
}
up
0
wodzuY2k at anronet dot pl
17 years ago
This function will help you dump any variable into XML structure.

        //dump var into simple XML structure
        function var_dump_xml($tagname,$variable,$level=0)
         {
            for($i=0;$i<$level;$i++) $marg.=' ';
            if (eregi('^[0-9].*$',$tagname)) $tagname='tag_'.$tagname; //XML tag cannot start with [0-9] character
            if (is_array($variable))
             {
                echo $marg."<$tagname>\n";
                while (list ($key, $val) = each ($variable))  var_dump_xml($key,$val,$level+1);
                echo $marg."</$tagname>\n";
             }
            elseif (strlen($variable)>0)
             {
                 echo $marg."<$tagname>".htmlspecialchars($variable)."</$tagname>\n";
             };    
         };
        
        /*
        example:
       
        $myVar = array("name"=>"Joe", "age"=>"26", "children"=>array("Ann","Michael"));
        var_dump_xml("myVarTag",$myVar);
        */
up
0
Anonymous
17 years ago
I usually work a lot with 2D arrays. Since I've had some trouble traversing them correctly maybe someone out there also experienced those problems and can use this one.

It's based on a 2D-array called $array[$x][$y]. At some (but not necessarily all) (x,y) there is a value I want to reach. Note that I do not know beforehand the ranges of $x or $y (that is their highest and lowest values).

while (list ($x, $tmp) = each ($array)) {
   while (list ($y, $val) = each ($tmp)) {
      echo "$x, $y, $val";
   }
}

The answer for each (x,y) pair can thus be (providng, of course those values where in your array beforehand):

1, 1, 2
2, 2, 0
3, 1, 1
5, 2, 2
5, 1, 2

Note that only the (x,y) pairs with a corresponding value is shown.

Hang in there
Jon Egil Strand
NTNU
up
0
tk at turtle-entertainment dot de
18 years ago
Be sure to use the integrated functions "unset();" or "reset();" - many people forget this and wonder about the created output!
up
-1
php at omit dot ianco dot co dot uk
11 years ago
I wanted to be able to add to an array while looping through it. foreach does not allow this because it is using a secret copy of the array. each makes this possible (tested on PHP 4).
<?php
$shopping_list
= array('oysters', 'caviare');
reset ($shopping_list);
while (list(
$key, $value) = each ($shopping_list)) {
    if (
$value == 'oysters') $shopping_list[] = 'champagne';
    elseif (
$value == 'champagne') $shopping_list[] = 'ice';
}
print_r($shopping_list);
// Array ( [0] => oysters [1] => caviare [2] => champagne [3] => ice )
?>
up
-2
gaviel
8 years ago
Ok Here's one for iterating multidimensional array .. using foreach

    <?php
        $members
= array(
                           
"member1" => array (
                                               
"First Name" => "Robert",
                                               
"Last Name" => "Burton",
                                               
"Age" => "20"
                                               
),
                           
"member2" => array (
                                               
"First Name" => "Cheska",
                                               
"Last Name" => "Vladesk",
                                               
"Age" => "21"
                                               
),
                           
"member3" => array (
                                               
"First Name" => "Gino",
                                               
"Last Name" => "Marley",
                                               
"Age" => "19"
                                               
),   
                           
"member4" => array (
                                               
"First Name" => "Jake",
                                               
"Last Name" => "White",
                                               
"Age" => "16"
                                               
),
                            );       
       
$dataSetCount = count($members);
        echo
"<h1>There are $dataSetCount members</h1>";   
       
       
$i = 0;
        foreach (
$members as $each_members) {
           
$i++;
            echo
"<h2>Member $i</h2>";
                foreach (
$each_members as $position => $details) {
                    echo
"<b>$position</b>" . ": " . $details . "<br />";
                }
            }
   
?>
up
-2
kris at angelanthony dot com
18 years ago
Remember to use "reset()" if you iterate over an array with "each()" more than once!  Example:

while(list($key,$value) = each($array)){
// code here
}

NOW the internal pointer on $array is at the end of the array, and another attempt at an iteration like the one above will result in zero executions of the code within the "while" block.  You MUST call "reset($array)" to reset the internal array pointer before iterating over the array again from the first element.
up
-6
ayyappan dot ashok at gmail dot com
3 years ago
/* Iterating using objects via each */

class SAI
{
   public function __toString()
   {     
          return __CLASS__;
   }
}
$a = new SAI();
$b = new SAI();
$c = new SAI();
$d = new SAI();
$e = new SAI();

$objarray = array($a,$b,$c,$d,$e);
reset($objarray);
while (list($key, $val) = each($objarray))
{
    echo "$key => $val\n";
}
//Results
0 => SAI
1 => SAI
2 => SAI
3 => SAI
4 => SAI

Warning:
each() will also accept objects, but may return unexpected results. It's therefore not recommended to iterate though object properties with each().
up
-4
nino dot skopac at gmail dot com
4 years ago
<?php
function each_v2($arr) {
   
// same as each() but when it hits end of array, it resets it
   
static $i = 0;
   
    if (isset(
$arr[$i])) {
       
// exists¸
       
return $arr[$i++];
    } else {
       
// reset $i to 0 and repeat
       
$i = 0;
        return
each_v2($arr);
    }
}
?>
up
-11
janhsh at tiscalinet dot be
1 year ago
The following example is invalid in PHP 7 :

<?php
$fruit
= array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list(
$key, $val) = each($fruit)) {
    echo
"$key => $val\n";
}
?>

The correct writing is
<?php
$fruit
= array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (
$Item= each($fruit)) {
   
$key=$Item[0];
   
$val=$Item[1];
    echo
"$key => $val\n";
}
?>

This is because the "list ()" command on the left no longer works in PHP 7 and there is no replacement command.
Which is very deplorable because this command was strongly used and allowed in a simple way to assign variables from array.
To Top