Php--for/foreach

Source: Internet
Author: User
Tags unpack

For

(PHP 4, PHP 5)

The For loop is the most complex loop structure in PHP. Its behavior is similar to the C language. The syntax for the For loop is:

for (EXPR1; expr2; expr3)    statement

the first expression (EXPR1) is evaluated unconditionally (and executed) at a time before the loop begins.

The EXPR2 is evaluated before each cycle begins. If the value is TRUE, the loop continues and the nested loop statement is executed. If the value is FALSE, the loop is terminated.

The EXPR3 is evaluated (and executed) after each loop.

Each expression can be empty or include multiple expressions separated by commas. In expression expr2, all expressions separated by commas are evaluated, but only the last result is taken. Expr2 is empty means that the infinite loop goes down (like C, PHP secretly considers its value to be TRUE). This may not be as useless as you might think, because you often want to end a loop with a conditional break statement instead of using the for expression truth.

Consider the following examples, which show numbers 1 through 10:

<?php/* Example 1 */for ($i = 1; $i <=, $i + +) {    echo $i;} /* Example 2 */for ($i = 1;; $i + +) {    if ($i >) {break        ;    }    echo $i;} /* Example 3 */$i = 1;for (;;) {    if ($i >) {break        ;    }    echo $i;    $i + +;} /* Example 4 */for ($i = 1, $j = 0; $i <=; $j + = $i, print $i, $i + +); >

of course, the first example looks the most concise (or someone thinks it's the fourth one), but the user may find it convenient to use an empty expression in a for loop for many occasions.

PHP also supports substitution syntax for a for loop with colons.

for (EXPR1; expr2; expr3):    statement;    ... endfor;

Sometimes it is often necessary to traverse an array as in the following example:

<?php/* * This array will change the value of some of these cells during traversal */$people = array (        ' name ' = ' Kalle ', ' salt ' = = 856412),         Array (' Name ' = ' Pierre ', ' salt ' and ' 215863 ')        ; for ($i = 0; $i < sizeof ($people); + + $i) {    $people [$i] [' salt '] = Ran D (000000, 999999);}? >

The above code may perform very slowly, because the length of the array is computed once for Each loop. Since the length of the array is always constant, you can use an intermediate variable to store the length of the array to optimize instead of constantly calling count ():

<?php$people = Array (        ' name ' = ' Kalle ', ' salt ' = ' 856412 '),         Array (' name ' = ' Pierre ', ' salt ' =& Gt 215863)        ), for ($i = 0, $size = sizeof ($people), $i < $size, + + $i) {    $people [$i] [' salt '] = rand (000000, 999999);} ?>

Foreach

(PHP 4, PHP 5)

The foreach syntax structure provides an easy way to iterate through an array. foreach can only be applied to arrays and objects, if you try to apply a variable to another data type, or an uninitialized variable will emit an error message. There are two kinds of syntax:

foreach (array_expression as $value)    Statementforeach (array_expression as $key = $value)    statement

the first format iterates through the given array of array_expression. In each loop, the value of the current cell is assigned to the $value and the pointer inside the array is moved forward one step (so the next cell in the next loop will be taken).

The second format does the same thing, except that the key name of the current cell is assigned to the variable $key in each loop.

You can also customize the traversal of objects.

Note:

When foreach starts executing, the pointer inside the array automatically points to the first cell. This means that you do not need to call Reset () before the Foreach loop.

Because foreach relies on an internal array pointer, modifying its value in a loop can cause unexpected behavior.

You can easily modify the elements of an array by adding & to it before $value. This method assigns a value to a reference instead of copying a value.

<?php$arr = Array (1, 2, 3, 4), foreach ($arr as & $value) {    $value = $value * 2;} $arr is now Array (2, 4, 6, 8) unset ($value); Finally, remove the reference?>

A reference to a $value is available only if the array being traversed can be referenced (for example, a variable). The following code does not work:

<?phpforeach (Array (1, 2, 3, 4) as & $value) {    $value = $value * 2;}? >

The $value reference of the last element of the warning array remains after the Foreach loop. It is recommended to use unset () to destroy it.


Note:

foreach does not support the ability to suppress error messages with "@".

The user may notice that the following code functions exactly the same:

<?php$arr = Array ("One", "one", "one", "three"), Reset ($arr), while (list (, $value) = each ($arr)) {    echo ' value: $value < Br>\n ";} foreach ($arr as $value) {    echo "value: $value <br/>\n";}? >

The following code functions are identical:

<?php$arr = Array ("One", "one", "one", "three"), Reset ($arr), while (List ($key, $value) = each ($arr)) {    echo ' key: $key; Value: $value <br/>\n ";} foreach ($arr as $key = $value) {    echo "key: $key; Value: $value <br/>\n ";}? >

More examples of demonstration usage:

<?php/* foreach Example 1:value only */$a = array (1, 2, 3, +), foreach ($a as $v) {   echo "current value of \ $a: $v . \ n ";} /* foreach example 2:value (with it manual access notation printed for illustration) */$a = array (1, 2, 3, +); $i = 0; /* For illustrative purposes only */foreach ($a as $v) {    echo "\ $a [$i] + $v. \ n";    $i + +;} /* Foreach example 3:key and value */$a = array ("one" + = 1, "one" + =    2,    "three" + 3, "    seventee ($a as $k = + $v) {    echo "\ $a [$k] + $v. \ n";} /* foreach Example 4:multi-dimensional arrays */$a = array (), $a [0][0] = "a"; $a [0][1] = "B"; $a [1][0] = "Y"; $a [1][1] = "Z"; foreach ($a as $v 1) {    foreach ($v 1 as $v 2) {        echo "$v 2\n";    }} /* Foreach Example 5:dynamic arrays */foreach (Array (1, 2, 3, 4, 5) as $v) {    echo "$v \ n";}? >

Unpack nested arrays with list ()

(PHP 5 >= 5.5.0)

PHP 5.5 adds the ability to iterate through an array of arrays and unpack the nested array into a loop variable by simply supplying the list () as a value.

For example:

<?php$array = [    [1, 2],    [3, 4],];foreach ($array as List ($a, $b)) {    //$a contains the first element of the Nested array,    //And $b contains the second element.    echo "A: $a; B: $b \ n ";}? >

The above routines will output:

a:1; B:2a:3; B:4

The cells in list () can be less than the nested arrays, and the extra array cells are ignored:

<?php$array = [    [1, 2],    [3, 4],];foreach ($array as List ($a)) {    //Note that there are no $b here.    echo "$a \ n";}? >

The above routines will output:

13

If more cells are listed in list () than nested arrays, a message-level error message is emitted:

<?php$array = [    [1, 2],    [3, 4],];foreach ($array as List ($a, $b, $c)) {    echo "a: $a; B: $b; C: $c \ n ";}? >

The above routines will output:

notice:undefined Offset:2 in example.php on line 7a:1; B:2; c:notice:undefined Offset:2 in example.php on line 7a:3; B:4; C:
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.