PHP foreach


foreach() function loops through an array.

<?PHP
	$arr=array(1,2,3,4,5);
	foreach($arr as $i) echo "$i, ";  //1, 2, 3, 4, 5, 
?>

foreach() can also loop through associative array.
<?PHP
	$arr=array("apple"=>"carbon","rice"=>"carbon","nuts"=>"fat","meat"=>"protein");
	foreach($arr as $key=>$val) echo "$key, $val; "; 
	//apple, carbon; rice, carbon; nuts, fat; meat, protein; 
?>

The associative array can also be looped through by using list(x,y)=each(array):
<?PHP
	$arr=array("apple"=>"carbon","rice"=>"carbon","nuts"=>"fat","meat"=>"protein");
	while (list($key,$val) = each($arr)) echo "$key, $val; "; 
	//apple, carbon; rice, carbon; nuts, fat; meat, protein; 
?>

A more complicated example:
<?PHP
	$arr=array("apple"=>"carbon","rice"=>"carbon","nuts"=>"fat","meat"=>"protein");
	while (list($key,$val) = each($arr)) 
	{
	   if (preg_match("/mea/",$key)) break;
	   echo "$key, $val; ";  //apple, carbon; rice, carbon; nuts, fat; 
	}
?>