foreach as php — 5 Real-World Examples You Can Use Today
The foreach loop in PHP (using the as keyword) is the easiest way to iterate arrays and objects. Below are five clear, Blogger-friendly examples (each code block is escaped so it displays correctly in the post).
1) Indexed Array (simple list)
Use this when you have a plain numeric-indexed array.
<?php $fruits = ["Apple", "Banana", "Cherry"]; foreach ($fruits as $fruit) { echo $fruit . "<br>"; } ?>
2) Associative Array (key => value)
Great for mapping keys to values (like name => age).
<?php $person = [ "name" => "John", "age" => 25, "city" => "New York" ]; foreach ($person as $key => $value) { echo $key . ": " . $value . "<br>"; } ?>
3) Multidimensional Array
Use for arrays containing arrays (e.g., list of users).
<?php $users = [ ["name" => "Alice", "age" => 22], ["name" => "Bob", "age" => 30] ]; foreach ($users as $user) { echo "Name: " . $user["name"] . ", Age: " . $user["age"] . "<br>"; } ?>
4) Objects (iterate public properties)
You can loop over an object to read its public properties.
<?php class Car { public $brand = "Toyota"; public $model = "Corolla"; public $year = 2022; } $car = new Car(); foreach ($car as $prop => $val) { echo $prop . ": " . $val . "<br>"; } ?>
5) Mixed Data Types (strings, numbers, booleans)
Handle arrays that contain different data types. Use var_dump()
to inspect values when needed.
<?php $mixed = ["Hello", 123, 3.14, true, null]; foreach ($mixed as $item) { var_dump($item); // shows type + value echo "<br>"; } ?>
Comments
Post a Comment