PHP Introduction | Control Structures | Repeating Arrays with foreach Statements
There is actually another repetition statement. It is a loop dedicated to processing every element of an array or associative array. It is written in the following forms.
For an array
foreach ($array as $variable) {
...... repeated processing ......
}
For an associative array
foreach ($array as $variable1 => $variable2) {
...... repeated processing ......
}
Arrays and associative arrays are written slightly differently.
- For an array, write
"$array as $variable"afterforeach. This lets you take values from the array on each iteration and assign them to the variable afteraswhile repeating the processing. - For an associative array, write two variables in the
foreachstatement,"$variable => $variable", instead of a single"$variable". Then the key is assigned to the first variable, and the value for that key is assigned to the second variable.
Here is a simple example.
<?php
$arr1 =array("Hello","Welcome","Hi");
$result1 = "";
foreach($arr1 as $item){
$result1 .= $item . " ";
}
$arr2 = array("ko"=> "하나", "ja"=> "いち","en"=>"one");
$result2 = "";
foreach($arr2 as $key=>$val){
$result2 .= $key . ":" . $val . "<br/>";
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8" />
<title>sample page</title>
</head>
<body>
<h1>Hello PHP!</h1>
<p><?php echo $result1; ?></p>
<p><?php echo $result2; ?></p>
</body>
</html>
This example creates an array and an associative array and outputs all their elements at once. By looking at how every element of the array and associative array is obtained, you can understand how foreach works.
foreach is a repetition statement dedicated to arrays and associative arrays. In particular, associative arrays cannot retrieve values by number, so an ordinary for statement cannot be used. Remember that foreach is required to iterate through an associative array.