Added foreach documentation

git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@17016 c90b9560-bf6c-de11-be94-00142212c4b1
This commit is contained in:
Joey Smith 1999-12-10 21:26:42 +00:00
parent 48e23c2035
commit 9dca6e84a5

View file

@ -416,7 +416,62 @@ for (expr1; expr2; expr3) statement
Other languages have a foreach statement to traverse an array or
hash. PHP uses the while statement and the <function>list</function>
and <function>each</function> functions for this. See the
documentation for these functions for an example.</para></sect1>
documentation for these functions for an example.</para>
<para>
A foreach statement has been added to PHP4. There are two supported
syteaxes:</para>
<para>
foreach(array_expression as $v): This will loop through array_expression
assigning the value of the array at the current position to $v, and then
advances the postion by one. See examples 1 and 2 below.</para>
<para>
foreach(array_expression as $k => $v): This will loop through
array_expression assigning the key of the array at the current position
to $k and the value of the array at the current position to $v, and then
advances the postion by one. See example 3 below.</para>
<informalexample>
<programlisting>
/* foreach example 1: value only */
$a = array(1, 2, 3, 17);
foreach($a as $v)
{
print "Current value of \$a: $v.\n";
}
/* foreach example 2: value (with key printed for illustration) */
$a = array(1, 2, 3, 17);
$i = 0; /* for illustrative purposes only */
foreach($a as $v)
{
print "\$a[$i] => $k.\n";
}
/* foreach example 3: key and value */
$a = array("one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17);
foreach($a as $k => $v)
{
print "\$a[$k] => $v.\n";
}
</programlisting>
</informalexample>
</sect1>
<sect1 id="control-structures.break">