what are the difference between for loop & for each loop in php

前端 未结 8 1984
庸人自扰
庸人自扰 2021-01-04 09:24

What are the differences between the for loop and the foreach loop in PHP?

8条回答
  •  余生分开走
    2021-01-04 10:16

    foreach is specifically for iterating over elements of an array or object.

    for is for doing something... anything... that has a defined start condition, stop condition, and iteration instructions.

    So, for can be used for a much broader range of things. In fact, without the third expression - without the iteration instructions - a for becomes a while.

    Examples:

    // Typical use of foreach
    // It's strength is iterating over arrays & objects
    $people = array("Tom", "Dick", "Hairy");
    
    foreach ($people as $person) {
        echo "$person 
    "; }

    Working example

    Now you could do the exact same thing with for, but why bother? Instead for can be used for completely different things:

    // Prints random names from array until Hairy is picked
    for ($people = array("Tom", "Dick", "Hairy"); // initial condition
         $people[0] != "Hairy";                   // stop condition
         shuffle($people)                         // iteration instructions
        ) {
        echo "$people[0] 
    "; }

    Working example

    The initial condition is done before the for loop once, no matter what. If the stop condition evaluates to false the loop will be immediately stopped. The change instructions are performed at the end of each loop. Notice that the change instructions don't have to be increments.

    Here is an example of turning a for loop into a while loop by leaving out the iteration instructions.

    // Does the loop a random number of times.
    // No thired expression
    for ($rand = function() {$array = array(true, true, true, true, false);
             shuffle($array);
             return $array;
            };                   
         current($rand()); 
         // empty third expression
     ) {  
    
        echo "I bring nothing to the table.
    "; }

    Working example

提交回复
热议问题