PHP Basic Tutorial
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.
foreach ($array as $value) { // Code to execute with $value }
Here, $value
represents the current element in the array during each iteration.
Try it yourself
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.
foreach
with Key and Valueforeach ($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.Try it yourself
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.
Try it yourself