Advertisement
Google Ad Slot: content-top
PHP foreach Loop
The foreach loop in PHP is specifically designed to work with arrays and objects, making it an efficient and easy way to iterate over elements. It is particularly useful when you need to access each value or key-value pair in an array without worrying about the index.
Syntax
foreach ($array as $value) {
// Code to execute with $value
}
Here, $value represents the current element in the array during each iteration.
Keys and Values
Using the foreach loop with both key and value is very useful when working with associative arrays in PHP. This allows you to access both the keys and the values of an array during each iteration.
Syntax for foreach with Key and Value
foreach ($array as $key => $value) {
// Code to execute with $key and $value
}
$key: This variable stores the current key.$value: This variable stores the current value for that key.
The foreach Loop on Objects
You can use the foreach loop to iterate over objects as well as arrays. When working with objects, foreach allows you to access the object's properties in a similar way to arrays.