Top 10 of PHP learning: foreach
PHP 4 (not PHP 3) includes the foreach structure, which is similar to Perl and other languages. This is just a simple way to traverse arrays. Foreach can only be used for arrays. an error occurs when you try to use it for another data type or an uninitialized variable. There are two types of syntax. The second type is secondary, but it is the first type of useful extension.
foreach (array_expression as $value) statementforeach (array_expression as $key => $value) statement |
The first format traverses the given array_expression array. In each loop, the value of the current unit is assigned to $ value and the pointer inside the array moves forward (so the next unit will be obtained in the next loop ).
In the second format, only the key values of the current unit are assigned to the variable $ key in each loop.
Note: When foreach starts to execute, the pointer inside the array automatically points to the first unit. This means that you do not need to call reset () before the foreach loop ().
Note: foreach operates on a copy of the specified array, rather than the array itself. Therefore, even if each () is constructed, the original array pointer is not changed, and the value of the array unit is not affected.
Note: foreach does not support "@" to prohibit error messages.
You may notice that the following code functions are identical:
$ Arr = array ("one", "two", "three "); Reset ($ arr ); While (list (, $ value) = each ($ arr )){ Echo "Value: $ value \ N "; }
Foreach ($ arr as $ value ){ Echo "Value: $ value \ N "; } ?> |
The following code has the same functions:
Reset ($ arr ); While (list ($ key, $ value) = each ($ arr )){ Echo "Key: $ key; Value: $ value \ N "; }
Foreach ($ arr as $ key => $ value ){ Echo "Key: $ key; Value: $ value \ N "; } ?> |
More examples of demo usage:
/* 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 authentication )*/
$ A = array (1, 2, 3, 17 );
$ I = 0;/* for each strative purposes only */
Foreach ($ a as $ v ){ Print "\ $ a [$ I] => $ v. \ n "; $ I ++; }
/* 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 "; }
/* Foreach example 4: multi-dimen1_arrays */
$ A [0] [0] = ""; $ A [0] [1] = "B "; $ A [1] [0] = "y "; $ A [1] [1] = "z ";
Foreach ($ a as $ v1 ){ Foreach ($ v1 as $ v2 ){ Print "$ v2 \ n "; } }
/* Foreach example 5: dynamic arrays */
Foreach (array (1, 2, 3, 4, 5) as $ v ){ Print "$ v \ n "; } ?> |