📖 Scenario: Imagine you have a list of fruits and you want to say hello to each fruit one by one.
🎯 Goal: You will create a list of fruits, set up a counter, use a loop to greet each fruit, and then print all greetings.
📋 What You'll Learn
Create an array called fruits with the values 'Apple', 'Banana', and 'Cherry'
Create a variable called count and set it to 0
Use a while loop with the condition $count < count($fruits)
Inside the loop, print Hello, followed by the fruit at index $count
Increment $count by 1 inside the loop
💡 Why This Matters
🌍 Real World
Loops are used in real life to do repeated tasks like sending emails to many people or checking every item in a list.
💼 Career
Knowing loops is important for any programming job because they help automate repetitive work efficiently.
Progress0 / 4 steps
1
Create the fruits array
Create an array called $fruits with these exact values: 'Apple', 'Banana', and 'Cherry'
PHP
Hint
Use square brackets to create the array and separate values with commas.
2
Set up the counter
Create a variable called $count and set it to 0
PHP
Hint
This variable will help us keep track of which fruit to greet next.
3
Use a while loop to greet each fruit
Use a while loop with the condition $count < count($fruits). Inside the loop, print Hello, followed by the fruit at index $count. Then increase $count by 1
PHP
Hint
Remember to use count($fruits) to get the number of fruits and increase $count inside the loop.
4
Print the greetings
Run the program to print the greetings for each fruit using the loop you wrote
PHP
Hint
Make sure your program prints each greeting on a new line.
Practice
(1/5)
1. Why do we use loops in PHP programming?
easy
A. To stop the program from running
B. To store data in variables
C. To create new functions
D. To repeat a block of code multiple times without rewriting it
Solution
Step 1: Understand the purpose of loops
Loops allow repeating the same code many times without writing it again and again.
Step 2: Compare other options
Storing data, creating functions, or stopping programs are not the main reasons for loops.
Final Answer:
To repeat a block of code multiple times without rewriting it -> Option D
Quick Check:
Loops repeat code = D [OK]
Hint: Loops repeat code to avoid rewriting [OK]
Common Mistakes:
Thinking loops store data
Confusing loops with functions
Believing loops stop the program
2. Which of the following is the correct syntax to start a for loop in PHP?
easy
A. for ($i = 0; $i < 5; $i++) {
B. for i = 0 to 5 {
C. loop ($i = 0; $i < 5; $i++) {
D. foreach ($i = 0; $i < 5; $i++) {
Solution
Step 1: Identify correct PHP for loop syntax
PHP uses for ($i = 0; $i < 5; $i++) { to start a for loop.
Step 2: Check other options for syntax errors
Options B, C, and D use incorrect keywords or formats not valid in PHP.
Final Answer:
for ($i = 0; $i < 5; $i++) { -> Option A
Quick Check:
PHP for loop syntax = A [OK]
Hint: PHP for loops use semicolons and parentheses [OK]