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.

Example
<?php
$colors = ["red", "green", "blue", "yellow"];
foreach ($colors as $color) {
echo "Color: $color<br>";
}
?>
Try it yourself

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.
Example
<?php
$person = [
"name" => "Alice",
"age" => 25,
"city" => "New York"
];

foreach ($person as $key => $value) {
echo "$key: $value<br>";
}
?>
Try it yourself

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.

Example
<?php
class Person {
public $name = "Alice";
public $age = 30;
public $city = "New York";
}

$person = new Person();
foreach ($person as $property => $value) {
echo "$property: $value<br>";
}
?>
Try it yourself