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 is mvc in php?

530


What is constructors and destructors?

533


Why is php used for web development?

495


Why session timeout is important?

619


How is it possible to remove escape characters from a string?

570






What is the purpose of a query?

500


Do you know how to declare an array in php?

538


What is difference between mysql_connect and mysqli_connect?

499


What is repository in php?

524


What is use of mysqli_query in php?

511


Can we override magic methods in php?

534


How to convert strings to numbers in php?

551


What is traits? How it is used in php?

542


Why overriding is called runtime polymorphism?

522


How to get complete current page url in php?

553