From 9dca6e84a555d4ad4d9fb811c856a2c43005cb58 Mon Sep 17 00:00:00 2001 From: Joey Smith Date: Fri, 10 Dec 1999 21:26:42 +0000 Subject: [PATCH] Added foreach documentation git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@17016 c90b9560-bf6c-de11-be94-00142212c4b1 --- language/control-structures.xml | 57 ++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/language/control-structures.xml b/language/control-structures.xml index 1df018cf8c..495e5b1be4 100644 --- a/language/control-structures.xml +++ b/language/control-structures.xml @@ -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 list and each functions for this. See the - documentation for these functions for an example. + documentation for these functions for an example. + + + A foreach statement has been added to PHP4. There are two supported + syteaxes: + + + 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. + + + 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. + + + + +/* 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"; +} + + + + + +