0
0
PHPprogramming~15 mins

For loop execution model in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
For loop execution model
📖 Scenario: You are helping a small shop owner count how many items they have in stock. They have a list of item quantities and want to add them up using a for loop.
🎯 Goal: Build a PHP program that uses a for loop to add up all the quantities in an array and print the total.
📋 What You'll Learn
Create an array called quantities with the exact values: 3, 5, 2, 8, 6
Create a variable called total and set it to 0
Use a for loop with a variable i starting at 0, running while i is less than the length of quantities, and incrementing i by 1 each time
Inside the loop, add $quantities[$i] to $total
Print the value of $total
💡 Why This Matters
🌍 Real World
Counting items in stock is a common task in shops and warehouses to keep track of inventory.
💼 Career
Understanding loops and arrays is essential for programming tasks like data processing, reporting, and automation.
Progress0 / 4 steps
1
Create the quantities array
Create an array called quantities with these exact values: 3, 5, 2, 8, 6.
PHP
Need a hint?

Use square brackets [] to create an array in PHP.

2
Create the total variable
Create a variable called total and set it to 0.
PHP
Need a hint?

Use $total = 0; to create and set the variable.

3
Add a for loop to sum quantities
Use a for loop with variable i starting at 0, running while i is less than count($quantities), and incrementing i by 1 each time. Inside the loop, add $quantities[$i] to $total.
PHP
Need a hint?

Use count($quantities) to get the number of items in the array.

4
Print the total
Print the value of $total using echo.
PHP
Need a hint?

Use echo $total; to display the total sum.