15. The foreach Loop (Introduction)
The foreach loop is specifically designed for easily iterating over Arrays and Objects. It simplifies the process by handling the iteration index automatically, making the code much cleaner than using a standard for loop for array traversal.
Basic foreach Syntax (Value Only)
This syntax iterates through the array, providing access to the value of each element.
php
"; foreach ($fruits as $fruit) { echo "Advanced foreach Syntax (Key and Value)
This syntax is essential when working with associative arrays, allowing access to both the key (index) and the value.
php
'Alice', 'city' => 'New York', 'age' => 28 ]; foreach ($user_data as $key => $value) { echo ucfirst($key) . ": " . $value . ""; } /* Output: Name: Alice City: New York Age: 28 */ ?>
Note: We will explore arrays and the foreach loop in much greater detail in Module 3.