Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 967
user285007 Avatar asked Apr 07 '10 07:04

user285007


2 Answers

Foreach is great for iterating through arrays that use keys and values.

For example, if I had an array called 'User':

$User = array(
    'name' => 'Bob',
    'email' => '[email protected]',
    'age' => 200
);

I could iterate through that very easily and still make use of the keys:

foreach ($User as $key => $value) {
    echo $key.' is '.$value.'<br />';
}

This would print out:

name is Bob
email is [email protected]
age is 200

With for loops, it's more difficult to retain the use of the keys.

When you're using object-oriented practice in PHP, you'll find that you'll be using foreach almost entirely, with for loops only for numerical or list-based things. foreach also prevents you from having to use count($array) to find the total number of elements in the array.

like image 193
Lotus Notes Avatar answered Nov 11 '22 12:11

Lotus Notes


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 <br/>"; }

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] <br/>";
}

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.<br/>";
}

Working example

like image 24
Peter Ajtai Avatar answered Nov 11 '22 13:11

Peter Ajtai