Foreach Loop for Arrays in PHP
📖 Scenario: You are managing a small fruit shop. You have a list of fruits you sell, and you want to show each fruit's name to your customers.
🎯 Goal: Build a PHP script that uses a foreach loop to go through an array of fruits and print each fruit's name.
📋 What You'll Learn
Create an array called
fruits with the exact values: 'Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'Create a variable called
count and set it to 0Use a
foreach loop with the variable fruit to iterate over the fruits arrayInside the loop, increment
count by 1Inside the loop, print the current fruit's name on its own line
After the loop, print the total number of fruits using the
count variable💡 Why This Matters
🌍 Real World
Loops like foreach are used to process lists of items such as products, users, or messages in many real applications.
💼 Career
Understanding foreach loops is essential for PHP developers to handle arrays and collections efficiently in web development.
Progress0 / 4 steps