Asked 7 years ago
20 Jan 2017
Views 7363
lain

lain posted

each vs foreach in PHP


difference between foreach and each in PHP ?

both should be use for iteration . is each and foreach is identical ? if not identical as respect to functionality than what is difference between each and foreach in PHP ?


foreach($array){
//iteration
}
each($array){
//iteration
}


is each / foreach iterate same way ?
each vs foreach , pros and cons of each and foreach in PHP
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

basic difference between each and foreach is
each is iterate array for one element only and foreach is iterate array for all element .

either both each and foreach Return the current key and value pair from an array


$array = array(" i ","love","php");
$next = each($array);
print_r($next);//return first key value from array 

you cant use each like foreach

$array = array(" i ","love","php");
 each($array as $key=>$value){
print_r($value);
}

because its not made for iterate the whole array next by next until loop disrupted


foreach loop 


$array = array(" i ","love","php");
 foreach($array as $key=>$value){
print_r($value);
}

its almost same like while loop , only foreach have key value return at every iteration
Post Answer