What are the differences between the for loop and the foreach loop in PHP?
Better and easy answer is: Difference between Foreach and For Loop:-
1. Foreach Loop:- Details are following.
a) Foreach loop used when you have an array, without array it's not worked.
b) Loop working at the end of array count. For example an array have 5 value
then loop run 5 times.
c) Syntax is following.
$array = array("Surinder","Rahul","Manoj","Bharti","Rana","Manish");
Foreach($array as $name ){
echo "Employe Name is ".$name.".";
}
This will print as following.
Employe Name is Surinder.
Employe Name is Rahul.
Employe Name is Manoj.
Employe Name is Bharti.
Employe Name is Rana.
Employe Name is Manish.
2. For Loop:- Details are following.
a) For loop used according to condition.
b) Loop working at the end of given condition.
c) Syntax is following.
$array = array("Surinder","Rahul","Manoj","Bharti","Rana","Manish");
For($i=0;$i<6;$i++){
echo "Employe Name is ".$array[$i].";
}
At the place of 6,You can used count array function.
This will print as following.
Employe Name is Surinder.
Employe Name is Rahul.
Employe Name is Manoj.
Employe Name is Bharti.
Employe Name is Rana.
Employe Name is Manish.
These are the difference between Foreach and for loop.
For more info go there:http://ibmphp.blogspot.com/2012/10/difference-between-foreach-and-for-loop.html