ȸ¿ø°¡ÀԡžÆÀ̵ð/ºñ¹øã±â
ȨÀ¸·Î


PHP each
13³â Àü
(PHP 3, PHP 4 , PHP 5)

each --  ¹è¿­¿¡¼­ ÇöÀçÀÇ Å°¿Í °ª ½ÖÀ» ¹ÝȯÇÏ°í ¹è¿­ Ä¿¼­¸¦ ÀüÁø½ÃŲ´Ù
¼³¸í
array each ( array array)


array ¹è¿­¿¡¼­ ÇöÀçÀÇ Å°¿Í °ª ½ÖÀ» ¹ÝȯÇÏ°í ¹è¿­ Ä¿¼­¸¦ ÀüÁø½ÃŲ´Ù. ÀÌ Å°/°ª ½ÖÀº 4°³ ¿ø¼Ò¸¦ °®´Â ¹è¿­À» ¹ÝȯÇÑ´Ù. 0, 1, key, value ÀÌ´Ù. ¿ø¼Ò 0°ú key´Â ¹è¿­ ¿ø¼ÒÀÇ Å° À̸§À» Æ÷ÇÔÇÏ°í, 1°ú value´Â µ¥ÀÌÅ͸¦ Æ÷ÇÔÇÑ´Ù.

¹è¿­ÀÇ ³»ºÎ Æ÷ÀÎÅÍ°¡ ¹è¿­ÀÇ ³¡À» ¹þ¾î³ª¸é, each()´Â FALSE¸¦ ¹ÝȯÇÑ´Ù.

¿¹ 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()¿Í °°ÀÌ »ç¿ëÇÑ´Ù. ¿¹Á¦ÄÚµå´Â ´ÙÀ½°ú °°´Ù: ¿¹ 2. each()·Î ¹è¿­ »ç¿ëÇϱâ

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

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

/* Outputs:

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

*/
?>  



each()°¡ ¼öÇàµÇ¸é, ¹è¿­ Ä¿¼­´Â ¹è¿­ÀÇ ´ÙÀ½ ¿ø¼Ò·Î ¿Å°ÜÁö°Å³ª, ¹è¿­ÀÇ ³¡ÀÎ °æ¿ì¿¡´Â ¸¶Áö¸· ¿ø¼Ò¸¦ Åë°úÇÑ´Ù. each¸¦ »ç¿ëÇÏ¿© ´Ù½Ã ¹è¿­À» »ç¿ëÇÏ·Á¸é reset()À» »ç¿ëÇØ¾ß ÇÑ´Ù.


°æ°í
¹è¿­À» ´Ù¸¥ º¯¼ö·Î ÁöÁ¤ÇÏ´Â °ÍÀº ¿ø·¡ÀÇ ¹è¿­ Æ÷ÀÎÅ͸¦ ÃʱâÈ­ Çϴ°ÍÀ̱⠶§¹®¿¡, À§ ¿¹Á¦ÄÚµå´Â ·çÇÁ¾È¿¡¼­ $fruit¸¦ ´Ù¸¥ º¯¼ö·Î ÁöÁ¤ÇÏ°Ô µÇ¸é ¹«ÇÑ ·çÇÁ¸¦ À¯¹ßÇÒ¼ö ÀÖ´Ù.


key(), list(), current(), reset(), next(), prev(), foreach Âü°í.




add a note User Contributed Notes
each
matthew at mhalls dot net
04-Dec-2005 11:58
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.
amby2 at izh dot com
24-Nov-2005 05:55
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.
Sopinon
23-Jul-2005 12:17
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);
       }
   }
}
?>
james at gogo dot co dot nz
02-Nov-2004 03:29
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";
?>
panania at 3ringwebs dot com
01-Jan-2004 01:51
The last method for record sets is great if you don't know the number of rows returned from a query, but if you do there's an easier way...

$strSQL = "SELECT * FROM table WHERE id=1";
$RecordsetSelect = $db->runQuery ($strSQL);
$row_Recordset1 = mysql_fetch_assoc($RecordsetSelect);
while (list($key, $val) = each($row_Recordset1)) {
   echo "$key => $val\n";
}        
mysql_free_result($RecordsetSelect);

Here we know that only 1 record will be returned because of the WHERE criteria. (Of course this is dependent on you own DB schema.)
wodzuY2k at anronet dot pl
04-Aug-2002 07:41
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);
       */
Gillis at dancrea dot com
26-May-2002 05:13
I wrote a short and pretty simple script-x 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
wodzuY2k at anronet dot pl
08-May-2002 04:40
Yet another useful example of how to make globals out of the config file.

config file:
[section1]
value=foo

PHP result :
variable: $section1_value=foo;

function servicesConfig_makeGlobals()
{
   global $servicesConfig;
   $servicesConfig = parse_ini_file("servicesConfig.conf", TRUE);
   reset($servicesConfig);
   while (list ($section, $section_val) = each ($servicesConfig))
     {
         reset($servicesConfig[$section]);
       while (list ($key, $val) = each ($servicesConfig[$section]))
         {
           $GLOBALS[$section.'_'.$key]=$val;
         };    
     };    
};
13-Feb-2002 12:10
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
tk at turtle-entertainment dot de
29-Jan-2001 07:33
Be sure to use the integrated functions "unset();" or "reset();" - many people forget this and wonder about the created output!
kris at angelanthony dot com
25-Oct-2000 08:03
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.
aryn at aryn dot nu
29-Jul-2000 03:34
one way to get variables out of an array dynamically, while skipping the keys is this:

while( list($key,$value)=each($foo)) {
  if (!is_int($key)) {
   echo "$"."$key: $value\n";
   $$key = $value;
  }
}
(the echo line is just for displaying what is variables are getting set; ie: not needed.)
phpmanual at devin dot com
15-Jul-2000 12:26
Note further that each() performs a shallow copy
of the value side of an (assoc) array; if you need to iterate on deep structures, something like:<br>
reset($A); while (list($k,) = each($A)) {<br>
   $elem = &$A[$k];<br>
   /* ... */<br>
}<br>
Is needed.  Copy construction would be handy to have here.
ellenzhg at hotmail dot com
30-Mar-2000 08:06
<?php
//each.php

$foo = array( "Robert" => "Bob", "Seppo" => "Sepi" );
$bar = each( $foo );
$k = implode(array_keys($bar),",");
$v = implode(array_values($bar),",");
echo $k ."<br>";
echo $v;
?>

output:
1,value,0,key
Bob,Bob,Robert,Robert
Above example only be interpretered by PHP4.
ridcully at magnet dot at
22-Mar-2000 02:03
To output all entries of an array $a, do this

reset ($a);
while( $res=each($a) )
{
  echo "$res[1]<br>";
};

If you need the keys too, it's in $res[0].
pyxl at dont_spam_on_me dot jerrell dot com
16-Feb-2000 11:41
Ok, for you folks who are learning this, here's something that should help your comprehension of each(), because I bashed my brains for a while on this one.<br><br>
The first example indicates that each() spits out a 4-cell 1 dimensional array.  This is all fine and dandy until you get to the second example, where that seems to be thrown out the window, because though each() is still spitting out 4 array elements, the list() being used is set up to only accept 2 values, as it's being executed with only wo variables in it!<br><br>
For some folks, this might not be a problem, but I couldn't understand the mismatch - why was it done, and where did the array go that each() generated??  Well, upon executing that code, it turns out that the first two array elements of the 4 element array that each() creates are assigned to those two variables, and the last two array element values are just thrown away - they're totally ignored.  It's how PHP is written.<br><br>
Now, why do that?  Well, the example was definitely written more to show folks how to use each() to make life much easier when dealing with a particular operations array in PHP that a lot of people work with, but it also has the side effect (which hopefully my little explaination has made more palatable) of demonstrating how each() can act when being used with other functions that don't necessarily want all of each()'s input.
steve at juggler dot net
07-Feb-2000 09:02
As of PHP 4.0b3, the interpreter's not quite smart enough to manage the following:
while(list($k,$v)=each(array("first","second","third")) {

Instead, use:
$ary=array("first","second","third");
while (list($k,$v)=each($ary)) {
php-traversing-matrices at mark dot datasys dot net
29-Nov-1999 04:47
Traversing multidimensional arrays is
easy, especially if you know how many dimensions are involved. Suppose you have a structure returned from a database query, such as

$returned_rows[$row_number][$field_name]

To walk through each field, you
might try this:

while (
   list($row_number, $row_array)
     = each($query_result_array)
   ) {
   while (
     list($field_name, $field_value)
       = each($row_array)
   ) {
     ##
     ## $row_number has the
     ## current row number,
     ## $field_name hsa the current    
     ## field' name,
     ## $field_value has the current          ## field's value
   }
  }
}
ÃßõÃßõ : 272 Ãßõ ¸ñ·Ï
¹øÈ£ Á¦¸ñ
892
chop - ³¡ÀÇ °ø¹éÀ» Á¦°ÅÇÕ´Ï´Ù.
891
strrev - ¹®ÀÚ¿­ÀÇ ³»¿ëÀ» ¿ª¼øÀ¸·Î ¹Ù²Ù´Â ÇÔ¼ö
890
strlen - ¹®ÀÚ¿­ÀÇ ±æÀ̸¦ ¾Ë·ÁÁÖ´Â ÇÔ¼ö
889
strcmp - µÎ °³ÀÇ ¹®ÀÚ¿­À» ºñ±³
888
function_exists - ÇÔ¼ö°¡ Á¤ÀǵǾî ÀÖ´ÂÁö ¾Æ´ÑÁö¸¦
887
array_splice - ¹è¿­ÀÇ ÀϺθ¦ »èÁ¦Çϰųª ÁöÁ¤ÇÑ ³»...
886
array_shift - ¹è¿­ÀÇ ¸Ç ¾Õ ¿ä¼Ò¸¦ »èÁ¦
885
array_pop - ¹è¿­ÀÇ ³¡ ¿ä¼Ò¸¦ »èÁ¦
884
array_unshift - ¹è¿­ÀÇ ¸Ç ¾Õ¿¡ ÇÑ °³ ¶Ç´Â ±× ÀÌ»ó
883
array_push - ¹è¿­ÀÇ ³¡¿¡ ÇÑ °³ ¶Ç´Â ±× ÀÌ»óÀÇ ¿ä¼Ò
882
mySQL_select_db - DB¸¦ ¼±ÅÃÇÕ´Ï´Ù.
881
mysql_query - mysql¿¡ Äõ¸®¸¦ º¸³À´Ï´Ù
880
mysql_fetch_array - °¡Á®¿Â°ªÀ» ¿¬°ü¹è¿­·Î ¸®ÅÏÇÕ´Ï´Ù.
879
mysql_close - Á¢¼ÓÀ» Á¾·áÇÕ´Ï´Ù
878
mysql_connect - mysql¿¡ Á¢¼ÓÇÕ´Ï´Ù
877
sizeof - ¹è¿­ÀÇ Å©±â¸¦ ±¸ÇÕ´Ï´Ù
876
array_slice - ¹è¿­ÀÇ ÀϺκÐÀ» °¡Á®¿É´Ï´Ù.
875
array array_reverse - ¹è¿­ÀÇ °ªÀ» ¸®¹ö½º ÇÕ´Ï´Ù.
874
array_flip - Å°À̸§°ú °ªÀ» ¼­·Î ¹Ù²ß´Ï´Ù.
873
array - ¹è¿­»ý¼º
872
empty - º¯¼ö¿¡ °ªÀÌ ÀÖ´ÂÁö È®ÀÎ
871
settype - º¯¼öÇü ¼³Á¤
870
gettype - º¯¼öÇüÀ» ±¸ÇÕ´Ï´Ù.
869
'Â÷·®¹øÈ£' Á¤±Ô½Ä
PHP each
867
PHP ¹è¿­°ü·Ã ÇÔ¼ö
866
PHP Filter(ÇÊÅÍ)
865
PHP ¿À·ù ó¸®(Error Handling)
864
htmlspecialchars()
863
PHP ÆÄÀÏó¸®
¸ñ·Ï
¹ÂÁ÷Æ®·ÎÆ® ºÎ»ê±¤¿ª½Ã ºÎ»êÁø±¸ °¡¾ßµ¿ ¤Ó °³ÀÎÁ¤º¸Ãë±Þ¹æħ
Copyright ¨Ï musictrot All rights reserved.