0
0
PHPprogramming~15 mins

Foreach loop for arrays in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
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 0
Use a foreach loop with the variable fruit to iterate over the fruits array
Inside the loop, increment count by 1
Inside 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
1
Create the fruits array
Create an array called fruits with these exact values: 'Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'
PHP
Need a hint?

Use square brackets [] to create the array and separate the fruit names with commas.

2
Create a counter variable
Create a variable called count and set it to 0
PHP
Need a hint?

Use the = sign to assign the value 0 to the variable count.

3
Use a foreach loop to iterate over fruits
Use a foreach loop with the variable fruit to iterate over the fruits array. Inside the loop, increment count by 1 and print the current fruit's name on its own line.
PHP
Need a hint?

Use foreach ($fruits as $fruit) to loop. Use $count++ to add 1. Use echo to print.

4
Print the total number of fruits
After the loop, print the total number of fruits using the count variable with the exact text: Total fruits: X where X is the value of count.
PHP
Need a hint?

Use echo "Total fruits: $count\n"; to print the total count.