update : 2015.11.03
php.shukuma.com검색:
|
foreach(PHP 4, PHP 5) The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes: foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element). The second form will additionally assign the current element's key to the $key variable on each iteration. It is possible to customize object iteration.
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
<?php Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won't work:
<?php Warning
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
You may have noticed that the following are functionally identical:
<?php The following are also functionally identical:
<?php Some more examples to demonstrate usage:
<?php Unpacking nested arrays with list()(PHP 5 >= 5.5.0) PHP 5.5 added the ability to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value. For example:
<?php 위 예제의 출력: A: 1; B: 2 A: 3; B: 4 You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:
<?php 위 예제의 출력: 1 3 A notice will be generated if there aren't enough array elements to fill the list():
<?php 위 예제의 출력: Notice: Undefined offset: 2 in example.php on line 7 A: 1; B: 2; C: Notice: Undefined offset: 2 in example.php on line 7 A: 3; B: 4; C: |