what is the diffrence between for and foreach?

Answer Posted / jennifer

A for loop is run on a condition, and will run until the
condition is false. Usually this is a counter, and the
condition is a threshold. (It can also easily be run
backwards, using $i-- instead of $i++.)

- so if the loop is "for ($i = 0; $i < 10; $i++)", it will
run 10 times, with $i beieng equal to 0, then 1, then
2, ... then 9, then when it reaches 10 the condition is
false and it jumps out to the next statement after the loop.

It can also be run with a condition unrelated to the
counter, or with non-counter-related statements, but
usually a while loop is better for that (and the
possibility of an accidental endless loop is much greater).

- like "for ($size = 0; $bag == 'full'; $size += 5)" which
assumes that somewhere (hopefully) the variable $bag gets
set to 'full' within the loop at some point. $i is just
counting the number of times the loop runs (or number of
items in the bag, in this case).

A foreach runs through an array (counted or associative),
executing the code in the the loop once for each element of
the array, with the array element (and optionally, the
associated key) available as variables.

- so "foreach ($lineup as $person)" will run the code in
the loop once for each person.
- "foreach ($lineup as $position => $person)" will do the
same thing but make the $position variable available,
especially useful for associative arrays.

Is This Answer Correct ?    13 Yes 4 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are the different tables(engine) present in mysql, which one is default?

518


How can you upload a file using php?

553


What are the steps for the payment gateway processing?

536


What is the mysql injection?

555


Why is node js better than php?

612






How can you declare a constant variable in php?

567


Is php used for frontend or backend?

534


How to access a specific character in a string?

501


What is the output of the following php code?

499


What is the difference between php and javascript?

567


How to initiate a session in php?

659


Is nan in javascript?

520


How many days will it take to learn php?

533


Which have the fastest execution between mysql_fetch_array() and mysql_fetch_assoc()

1823


What is the function used to change the root directory in PHP?

560