PHP foreach
PHP Tutorial » PHP foreach
What is foreach in PHP?
The Foreach build in PHP provides an easy way to repeat over the array, foreach only works on arrays and objects and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
Syntax1:
Syntax2:
Customize object iteration.
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
foreach ($arr as $key => $value) {
echo "<br /> {$key} => {$value} ";
print_r($arr);
}
?>
Related subjects:
What is an array
Convert array to string comma
Array to comma separated
Associative array
String contains
What is foreach in PHP?
How do you iterate through an array in PHP?
What is the difference between for and foreach in PHP?
Which loop would you prefer to go through an array in PHP briefly describe?
Tags: php foreach: key value, break, index, continue, multidimensional array, loop, string, end foreach, associative array, last item
PHP foreach with indexed arrays
To iterate over all elements of an indexed array, you use the following syntax:
foreach ($array_name as $element) { // process element here }
<?php
$my_colors = ['white', 'yellow', 'black', 'green'];foreach ($my_colors as $color) {
echo $color . '<br />';
}
?>
PHP foreach with an associative array
To iterate over elements of an associative array, you use the following syntax:
foreach ($array_name as $key => $value) {
//process element here;
}
<?php
$country_capitals = [
'Austria' => 'Vienna',
'Spain' => 'Madrid',
'Italy' => 'Rome',
'Framce' => 'Paris',
'United States' => 'Washington D.C.'
];foreach ($country_capitals as $country => $capital) {
echo "The capital city of {$country} is $capital" . '<br />';
}
?>
php foreach: key value, break, index, continue, multidimensional array, loop, string, end foreach, associative array, last item
PHP foreach - php tutorial
This tool makes it easy to create, adjust, and experiment with custom colors for the web.

Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.

Find here examples of creative and unique website layouts.

Find here examples of creative and unique website CSS HTML menu.