Jump to: navigation, search

Php foreach

From w3cyberlearnings

Contents

foreach loop

foreach loops to iterate through an array or an associative array.


Syntax

foreach($arr as $aVal) {
      statement
}

OR

foreach($ass_aa as $key=>$value) {
      statement
}

Example 1

<?php

$score = array(23, 43, 23, 54, 52, 32);
foreach ($score as $s) {
	echo $s . "<br/>";
}
?>

Output

23
43
23
54
52
32

Example 2

<?php

$count = 5;
for ($i = $count; $i > 0; $i--) {
	echo $i . "<br/>";
}
?>

Output

5
4
3
2
1

Example 3: Use associative array within foreach loop

<?php

$student_list =
		  array(
			       'Sopheap Chan' => 'Cambodia',
				'Yiling Zheng' => 'China',
				'Misumi Suo' => 'Japan',
				'Johnny Lee' => 'South Korea');
foreach ($student_list as $key => $value) {
	echo $key . " is from " . $value . "<br/>";
}
?>
      

Output

Sopheap Chan is from Cambodia
Yiling Zheng is from China
Misumi Suo is from Japan
Johnny Lee is from South Korea


Related Links


Navigation
Web
SQL
MISC
References