In this article foreach Loop in PHP we give the information about the foreach loop is mainly used with arrays and objects. It operates on each element and provides access to one element in every iteration.
foreach Loop in PHP:
Syntax of foreach Loop
foreach ($array as $value) {
// code block
}
Or, if you need both key and value:
foreach ($array as $key => $value) {
// code block
}
Description of parts of syntax
- $array: The array on which the loop is being run.
- $key (optional): The key of the element.
- $value: Value of the element.
Example 1: foreach with values only
<?php
$fruits = [“apple”, “banana”, “orange”];
foreach ($fruits as $fruit) {
echo “Fruit: $fruit<br>”;
}
?>
Output:
Fruit: Apple
Fruit: Banana
Fruit: Orange
Example 2: Using both Key and Value
<?php
$students = [“Rahul” => 85, “Sonia” => 90, “Aman” => 75];
foreach ($students as $name => $marks) {
echo “Student: $name, Marks: $marks<br>”;
}
?>
Output:
Student: Rahul, Marks: 85
Student: Sonia, Marks: 90
Student: Aman, Marks: 75
Break Statement in foreach Loop (Break Statement)
break is used to stop the loop midway.
Example 3: foreach with break
<?php
$numbers = [10, 20, 30, 40, 50];
foreach ($numbers as $number) {
if ($number == 30) {
break; //The loop will stop at 30.
}
echo “Number: $number<br>”;
}
?>
Output:
Number: 10
Number: 20
Continue Statement in foreach Loop (Continue Statement)
continue is used to skip a particular iteration and move to the next.
Example 4: foreach with continue
<?php
$numbers = [10, 20, 30, 40, 50];
foreach ($numbers as $number) {
if ($number == 30) {
continue; //skip 30
}
echo “Number: $number<br>”;
}
?>
Output:
Number: 10
Number: 20
Number: 40
Number: 50
Complex Example: Use of both Break and Continue
<?php
$students = [
“Rahul” => 85,
“Sonia” => 90,
“Aman” => 75,
“ray” => 95,
“Ravi” => 50
];
foreach ($students as $name => $marks) {
if ($marks < 60) {
echo “Student $name omitted (low).<br>”;
continue; // Drop student with marks less than 60.
}
if ($name == “ray”) {
echo “Loop stopped at $name.<br>”;
break; // Stop the loop at “ray”.
}
echo “Student: $name, Marks: $marks<br>”;
}
?>
Output:
Student Rahul, Marks: 85
Student Sonia, Marks: 90
Student Aman, Mark: 75
The loop was stopped on the beam.
Conclusion
- The foreach loop is easy to use with arrays and objects.
- break is used to quickly stop a loop.
- continue is used to skip a particular iteration.
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining