Quick Reach
What is PHP foreach loop?
The foreach is a type of loop that is used to loop through array elements. While developing PHP programs, you will come across arrays and its manipulation.
See an example of foreach
The PHP foreach loop makes it quite easier to get through array elements.
The foreach loop structure
Following is the structure of foreach loop:
foreach ($array_name as $value) {
Statements to execute;
}
The foreach with an array
In PHP, the foreach is used to loop arrays. The foreach loop passes the value of the current element which is assigned to $value while array pointer is moved to the next element. In the next loop, the next element will be processed and this will go on until the last element.
As you are using a foreach loop with an array, rather having a counter that goes until proven false (like i++) the foreach loop goes on looping unless it has used all values in the array.
A foreach PHP example with a numeric array
The following example creates an array of five numeric elements followed by a foreach that will loop through the array and will display array elements. Look how simple it is to use the foreach in PHP:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php
$arr = array( 1, 2, 3, 4, 5);
foreach( $arr as $value )
{
echo “Value is $value <br />”;
}
?>
|
A foreach example with associative array
The following example creates an associative array with five elements for demo purpose. We will use the foreach loop to go through the array to display associative array elements.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?php
$arr = array( 1, 2, 3, 4, 5);
$associative_arr[“element1”]= “value1”;
$associative_arr[“element2”]= “value2”;
$associative_arr[“element3”]= “value3”;
$associative_arr[“element4”]= “value4”;
$associative_arr[“element5”]= “value5”;
foreach( $associative_arr as $value )
{
print “Current element is: $value <br />”;
}
?>
|
How to print PHP array with echo and print
Printing an array as a whole or by elements is easy in PHP. We can use the echo or print statements to accomplish that.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<?php
//Define an array
$emp_array[0] = “Mike”;
$emp_array[1] = “Sally”;
$emp_array[2] = “Charlie”;
$emp_array[3] = “Clare”;
// Print array in php program using echo statement
echo $emp_array[0];
echo $emp_array[1] . “</BR>”;
echo “employee number 3 is:” . $emp_array[2] . “</BR>”;
// Print array by using print statement
print $emp_array[0];
print $emp_array[1] . “</BR>”;
print “employee number 3 is:” . $emp_array[2];
?>
|
See also PHP For Loop | PHP Do While Loop | PHP Arrays
Leave A Comment?