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
<!DOCTYPE html>
<html>
<body>
<?php
$colors = ["red", "green", "blue", "yellow"];

foreach ($colors as $color) {
echo "Color: $color<br>";
}
?>
</body>
</html>

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

foreach ($person as $key => $value) {
echo "$key: $value<br>";
}
?>
</body>
</html>

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
<!DOCTYPE html>
<html>
<body>
<?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>";
}
?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.