php for loop

Part of the course: php for beginners

php for loop

Table of Contents: PHP for Loop

  1. Introduction to Loops in PHP

  2. Understanding the for Loop

  3. Components of a for Loop

  4. Your First for Loop Example

  5. Using for Loops with Numbers

  6. Working with Arrays Using for

  7. Nested for Loops

  8. Using break and continue

  9. Common Mistakes with for Loops

  10. Performance Tips

  11. Practical Examples and Exercises

  12. Summary and Next Steps

 

Introduction to Loops in PHP

In programming, we often need to repeat a block of code multiple times. Instead of writing the same code again and again, PHP provides loops to handle repetitive tasks efficiently. One of the most commonly used loops is the , which is ideal when the number of repetitions is known in advance.

Loops help developers write cleaner, shorter, and more maintainable code. Without loops, even simple tasks like printing numbers or processing a list would require unnecessary repetition.

What Are Loops and Why Do We Use Them?

A loop allows a piece of code to run repeatedly as long as a specific condition is true. For example, if you want to display numbers from 1 to 10, writing ten separate echo statements is inefficient. This is where a php for loop becomes very useful.

Example Without a Loop (Not Recommended)

echo 1;
echo 2;
echo 3;
echo 4;
echo 5;

Example Using php for loop (Recommended)

for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}

In this example, the php for loop automatically handles repetition, making the code shorter and easier to understand.

Types of Loops in PHP

PHP supports several types of loops, each designed for specific situations. Understanding these loops helps you choose the right one for your task.

1. php for loop

The php for loop is best used when you know exactly how many times the loop should run.

Syntax:

for (initialization; condition; increment) {
// code to execute
}

Practical Example:

for ($i = 0; $i < 3; $i++) {
echo "Hello World<br>";
}

This example prints “Hello World” three times using a php for loop.

2. while Loop

The while loop runs as long as a condition remains true. It is useful when the number of iterations is unknown.

$i = 1;
while ($i <= 3) {
echo $i . "<br>";
$i++;
}

3. do-while Loop

The do-while loop executes the code at least once, even if the condition is false.

$i = 1;
do {
echo $i . "<br>";
$i++;
} while ($i <= 3);

4. foreach Loop

The foreach loop is mainly used to iterate through arrays.

$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo $color . "<br>";
}

Why php for loop Is Important

Among all loop types, the php for loop is especially important because:

  • It is easy to read and control

  • It works perfectly with counters and indexes

  • It is commonly used in arrays, tables, and calculations

For example, displaying a list of users or generating a multiplication table is much easier with a php for loop.

Example: Multiplication Table Using php for loop

for ($i = 1; $i <= 10; $i++) {
echo "5 x $i = " . (5 * $i) . "<br>";
}
yo can read do while loop article also:php do while loop

Understanding the for Loop in PHP

The php for loop is one of the most commonly used control structures in PHP. It allows developers to execute a block of code repeatedly for a specific number of times. The php for loop is especially useful when the number of iterations is known in advance, such as looping through numbers, indexes, or fixed-length data.

By using a php for loop, you can avoid repetitive code and make your programs more efficient, readable, and easier to maintain.

Definition of the for Loop

A php for loop is a loop that runs based on three main expressions:

  1. Initialization of a counter

  2. A condition that must remain true

  3. An increment or decrement of the counter

As long as the condition is true, the code inside the php for loop will continue to execute.

Simple Definition:

The php for loop executes a block of code repeatedly until a specified condition becomes false.

Basic Syntax of the for Loop in PHP

The general syntax of a php for loop looks like this:

for (initialization; condition; increment) {
// code to be executed
}

Explanation of Each Part:

  • Initialization: Sets the starting value (usually a counter variable)

  • Condition: Determines how long the loop should run

  • Increment/Decrement: Updates the counter after each loop iteration

Simple Example of php for loop

The following example uses a php for loop to print numbers from 1 to 5:

for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}

How It Works:

  • $i = 1 → loop starts at 1

  • $i <= 5 → loop runs while this condition is true

  • $i++ → increases the value of $i by 1 each time

This is a basic but very common use of a php for loop.

Practical Example: Displaying a List

A php for loop is often used to display lists, such as product numbers or user IDs.

for ($i = 1; $i <= 3; $i++) {
echo "Product ID: " . $i . "<br>";
}

Output:

Product ID: 1
Product ID: 2
Product ID: 3

This practical example shows how a php for loop can dynamically generate content.

Using php for loop for Calculations

The php for loop is also useful for performing repeated calculations.

Example: Sum of Numbers

$sum = 0;

for ($i = 1; $i <= 10; $i++) {
$sum += $i;
}

echo “Total sum is: “ . $sum;

In this example, the php for loop calculates the total sum of numbers from 1 to 10.

Why Use php for loop?

The php for loop is ideal when:

  • You know the exact number of iterations

  • You are working with counters or indexes

  • You want clean and structured code

Common real-world uses include:

  • Generating tables

  • Processing indexed arrays

  • Repeating HTML elements

  • Running mathematical operations

Components of a for Loop in PHP

To fully understand how a php for loop works, it is important to learn about its three main components. Each component plays a specific role in controlling how many times the loop runs and when it stops. When these components are used correctly, the php for loop becomes a powerful and flexible tool for repetitive tasks.

The structure of a php for loop includes:

  • Initialization

  • Condition

  • Increment / Decrement

for (initialization; condition; increment/decrement) {
// code to execute
}

Let’s examine each component in detail with practical examples.

1. Initialization

Initialization is the first part of a php for loop. It is executed only once, at the beginning of the loop. This is where you usually define and set the starting value of the counter variable.

Example: Initialization in php for loop

for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}

In this example:

  • $i = 1 is the initialization

  • The loop starts counting from 1

Practical Use Case

Initialization is commonly used when:

  • Starting from the first item in a list

  • Beginning a count from zero or one

  • Defining an index for arrays

2. Condition

The condition determines how long the php for loop will continue to run. Before each iteration, PHP checks this condition. If the condition is true, the loop continues. If it becomes false, the loop stops.

Example: Condition in php for loop

for ($i = 1; $i <= 3; $i++) {
echo "Iteration: " . $i . "<br>";
}

In this php for loop:

  • $i <= 3 is the condition

  • The loop runs only while the condition remains true

Common Mistake

If the condition is written incorrectly, it may cause:

  • An infinite loop

  • The loop to never execute

Example of Incorrect Condition

for ($i = 1; $i >= 5; $i++) {
echo $i;
}

This php for loop will never run because the condition is false from the start.

3. Increment / Decrement

The increment or decrement part of a php for loop updates the counter after each iteration. This step ensures that the loop eventually reaches a point where the condition becomes false.

Example: Increment in php for loop

for ($i = 0; $i < 5; $i++) {
echo $i . "<br>";
}

Here:

  • $i++ increases the value of $i by 1 each time

Example: Decrement in php for loop

for ($i = 5; $i > 0; $i--) {
echo $i . "<br>";
}

This php for loop counts backward from 5 to 1.

Practical Example: Displaying Even Numbers

This example combines all components of a php for loop to display even numbers from 2 to 10.

for ($i = 2; $i <= 10; $i += 2) {
echo $i . "<br>";
}
  • Initialization: $i = 2

  • Condition: $i <= 10

  • Increment: $i += 2

This practical use of the php for loop is common in filtering and number-based logic.

Real-World Example: Looping Through Indexes

In many applications, a php for loop is used to work with indexes such as page numbers or item IDs.

for ($page = 1; $page <= 5; $page++) {
echo "Page " . $page . "<br>";
}

This php for loop simulates pagination numbering.

Your First for Loop Example in PHP

When learning PHP, one of the first and most important concepts to understand is the php for loop. This loop helps you repeat a block of code a specific number of times, which is very common in real-world programming tasks.

In this section, we will create our first php for loop, use it to print numbers, and then explain how it works step by step.

Printing Numbers Using a php for loop

Let’s start with a simple and practical example. The following php for loop prints numbers from 1 to 5:

for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}

Output:

1
2
3
4
5

This is one of the most basic and common uses of a php for loop, and it clearly shows how repetition works in PHP.

Step-by-Step Execution Explanation

To fully understand the php for loop, let’s break down what happens in each step of the loop execution.

Step 1: Initialization

$i = 1;
  • The php for loop starts by setting the counter variable $i to 1

  • This step runs only once

Step 2: Condition Check

$i <= 5;
  • PHP checks if the condition is true

  • Since $i is 1, the condition is true, so the loop continues

Step 3: Code Execution

echo $i . "<br>";
  • The code inside the php for loop runs

  • The current value of $i is printed

Step 4: Increment

$i++;
  • The value of $i increases by 1

  • $i becomes 2

Step 5: Repeat the Process

  • PHP checks the condition again

  • If the condition is still true, the php for loop runs again

  • This continues until $i becomes 6

Step 6: Loop Ends

  • When $i is 6, the condition $i <= 5 becomes false

  • The php for loop stops executing

Practical Example: Printing a Message Multiple Times

The php for loop is not limited to numbers. You can also use it to repeat text.

for ($i = 1; $i <= 3; $i++) {
echo "Welcome to PHP<br>";
}

Output:

Welcome to PHP
Welcome to PHP
Welcome to PHP

This example shows how a php for loop can be used to repeat messages, such as notifications or UI elements.

Real-World Example: Displaying Item Numbers

In real projects, a php for loop is often used to generate lists dynamically.

for ($i = 1; $i <= 4; $i++) {
echo "Item number: " . $i . "<br>";
}

This php for loop could represent product numbers, user IDs, or order items in a web application.

Using for Loops with Numbers in PHP

One of the most common uses of a for loop in PHP is working with numbers. Whether you need to count upward, count downward, or increase numbers by custom steps, the for loop provides full control over numeric repetition. This makes it especially useful for calculations, counters, reports, and generating dynamic content.

Counting Upward with a for Loop

Counting upward is the most basic numeric operation using a for loop. It is commonly used when you want to repeat an action starting from a small number and moving to a larger one.

Example: Counting from 1 to 5

for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}

Explanation:

  • The loop starts at 1

  • It runs as long as the condition is true

  • The counter increases by 1 after each iteration

Practical Use Case:

  • Displaying page numbers

  • Showing item indexes

  • Numbering rows in a table

Counting Downward with a for Loop

A for loop can also count backward by decreasing the counter value. This is useful in countdowns, timers, or reverse ordering.

Example: Counting from 5 down to 1

for ($i = 5; $i >= 1; $i--) {
echo $i . "<br>";
}

Explanation:

  • The loop starts at 5

  • The condition checks if the number is still greater than or equal to 1

  • The counter decreases by 1 each time

Practical Use Case:

  • Countdown timers

  • Reverse lists

  • Processing data from last to first

Using Custom Step Values in a for Loop

Sometimes you may want to increase or decrease numbers by more than one. The for loop allows you to define custom step values easily.

Example: Counting by 2 (Even Numbers)

for ($i = 2; $i <= 10; $i += 2) {
echo $i . "<br>";
}

Output:

2
4
6
8
10

Practical Use Case:

  • Displaying even or odd numbers

  • Skipping unnecessary values

  • Optimizing loops for performance

Example: Counting Down by 5

for ($i = 50; $i >= 0; $i -= 5) {
echo $i . "<br>";
}

This example is useful for score systems, price discounts, or progress indicators.

Real-World Example: Price Calculation with Steps

for ($price = 100; $price >= 50; $price -= 10) {
echo "Price: $" . $price . "<br>";
}

This loop simulates decreasing prices, such as discounts in an online store.

Working with Arrays Using for in PHP

Arrays are one of the most common data structures in PHP, and the for loop is often used to work with indexed arrays. When you need precise control over array indexes or want to perform operations based on position, using a for loop is an excellent choice.

Unlike foreach, the for loop allows you to directly access array elements using their numeric index.

Accessing Array Elements by Index

In PHP, indexed arrays store values with numeric keys starting from 0. You can access any element by using its index number.

Example: Accessing a Single Array Element

$colors = ["Red", "Green", "Blue"];

echo $colors[0]; // Output: Red
echo $colors[1]; // Output: Green

This direct access is useful when you need a specific position in the array.

Looping Through Indexed Arrays with for

To loop through an array using a for loop, you usually combine it with the count() function, which returns the total number of elements in the array.

Example: Looping Through an Indexed Array

$fruits = ["Apple", "Banana", "Orange"];

for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . “<br>”;
}

Explanation:

  • The loop starts at index 0

  • count($fruits) defines how many times the loop runs

  • $fruits[$i] accesses each element by index

Practical Example: Displaying a Product List

In real-world applications, indexed arrays often represent lists of data such as products or items.

$products = ["Laptop", "Phone", "Tablet", "Monitor"];

for ($i = 0; $i < count($products); $i++) {
echo “Product “ . ($i + 1) . “: “ . $products[$i] . “<br>”;
}

This example demonstrates how a for loop can generate a numbered product list dynamically.

Optimizing Array Loops

Calling count() inside the loop condition repeatedly can be inefficient for large arrays. A better approach is to store the array length in a variable.

Optimized Example:

$numbers = [10, 20, 30, 40, 50];
$length = count($numbers);

for ($i = 0; $i < $length; $i++) {
echo $numbers[$i] . “<br>”;
}

This method improves performance and is considered a best practice.

Practical Example: Calculating Total Using an Array

$prices = [100, 200, 150, 250];
$total = 0;
$length = count($prices);

for ($i = 0; $i < $length; $i++) {
$total += $prices[$i];
}

echo “Total Price: $” . $total;

This example shows how a for loop can be used to process array values for calculations.

When to Use for Instead of foreach

Using a for loop is recommended when:

  • You need the index value

  • You want to modify array elements by position

  • You are working with numeric indexes

  • You need full control over the loop counter

 

 

 

 

Nested for Loops in PHP

A nested for loop is a loop placed inside another loop. In PHP, nested for loops are commonly used when working with multi-dimensional data, tables, or repetitive patterns. Each time the outer loop runs, the inner loop runs completely.

Nested loops are very powerful, but they should be used carefully to avoid unnecessary complexity or performance issues.

What Are Nested Loops?

A nested loop means one loop inside another loop. The outer loop controls the main repetition, while the inner loop handles repeated actions within each outer loop cycle.

Basic Structure of Nested for Loops

for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo "i = $i, j = $j<br>";
}
}

Explanation:

  • The outer loop runs 3 times

  • For each outer loop iteration, the inner loop runs 3 times

  • Total executions: 3 × 3 = 9

Practical Example 1: Creating a Multiplication Table

One of the most common uses of nested for loops is generating a multiplication table.

for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= 5; $j++) {
echo $i * $j . " ";
}
echo "<br>";
}

Output:

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Use Case:

  • Math tables

  • Reports and grids

  • Educational tools

Practical Example 2: HTML Table Using Nested Loops

Nested for loops are often used to generate HTML tables dynamically.

echo "<table border='1'>";

for ($row = 1; $row <= 3; $row++) {
echo “<tr>”;
for ($col = 1; $col <= 4; $col++) {
echo “<td>Row $row, Col $col</td>”;
}
echo “</tr>”;
}

echo “</table>”;

Use Case:

  • Displaying database results

  • Creating dashboards

  • Dynamic layouts

Practical Example 3: Printing Star Patterns

Nested loops are useful for creating visual patterns such as stars or shapes.

Example: Right-Angled Triangle Pattern

for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo "*";
}
echo "<br>";
}

Output:

*
**
***
**
**
*****

Practical Example 4: Rectangle Pattern

for ($i = 1; $i <= 4; $i++) {
for ($j = 1; $j <= 6; $j++) {
echo "#";
}
echo "<br>";
}

This creates a rectangular pattern of characters.

When to Use Nested for Loops

Nested for loops are ideal when:

  • Working with rows and columns

  • Handling two-dimensional arrays

  • Generating tables or grids

  • Creating structured patterns

However, avoid deep nesting as it can make code harder to read and slower to execute.

Using break and continue in PHP for Loops

The php for loop allows you to repeat code, but sometimes you need more control over the loop’s behavior. This is where the break and continue statements become very useful.

  • break: Stops the loop entirely and exits.

  • continue: Skips the current iteration and moves to the next one.

These statements make your php for loop more flexible and powerful.

1. Stopping a Loop with break

The break statement immediately terminates the loop when a specific condition is met. It is useful when you want to stop looping once a goal is achieved.

Example: Stopping a Loop When a Number is Found

for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Stop the loop when $i equals 5
}
echo $i . "<br>";
}

Output:

1
2
3
4

Practical Use Case:

  • Searching for a value in a list

  • Stopping a loop when a condition is met (e.g., out-of-stock item)

2. Skipping Iterations with continue

The continue statement skips the current iteration and immediately moves to the next one. It is helpful when you want to ignore certain values but continue the loop.

Example: Skipping Even Numbers

for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo $i . "<br>";
}

Output:

1
3
5
7
9

Practical Use Case:

  • Filtering out unwanted items

  • Ignoring invalid or empty data in loops

  • Skipping specific conditions without stopping the entire loop

3. Combining break and continue

You can use both break and continue in a single php for loop to handle more complex logic.

Example: Skip Some Numbers and Stop at a Limit

for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
if ($i > 7) {
break; // Stop loop when $i is greater than 7
}
echo $i . "<br>";
}

Output:

1
3
5
7

Practical Use Case:

  • Complex filtering

  • Processing only specific items

  • Efficient loop control in large datasets

 

Common Mistakes with for Loops in PHP

While the php for loop is a powerful tool, beginners and even experienced developers sometimes make mistakes that lead to unexpected results. Understanding these common errors can help you write more reliable and efficient loops.

The most frequent mistakes include:

  1. Infinite Loops

  2. Incorrect Conditions

  3. Off-by-One Errors

1. Infinite Loops

An infinite loop occurs when the loop’s terminating condition is never met. This can freeze your application or server if not handled correctly.

Example of an Infinite Loop:

for ($i = 1; $i > 0; $i++) {
echo $i . "<br>";
}
  • Condition $i > 0 is always true

  • The loop never stops

How to Fix:

  • Ensure the condition will eventually become false

  • Use proper increment/decrement logic

for ($i = 1; $i <= 10; $i++) {
echo $i . "<br>"; // Loop stops when $i > 10
}

2. Incorrect Conditions

Using the wrong condition can cause the loop to either never run or behave unexpectedly.

Example: Loop Never Runs

for ($i = 5; $i < 1; $i++) {
echo $i . "<br>";
}
  • The condition $i < 1 is false from the start

  • The loop does not execute at all

Example: Loop Runs Too Many Times

for ($i = 1; $i <= 10; $i--) {
echo $i . "<br>";
}
  • Counter decreases instead of increases

  • Condition $i <= 10 remains true, creating an infinite loop

How to Fix:

  • Double-check the logic for the loop condition and the counter

3. Off-by-One Errors

An off-by-one error happens when the loop executes one time too few or too many. This often occurs when using <= or < incorrectly.

Example: Missing the Last Element

for ($i = 0; $i < 5; $i++) {
echo $i . "<br>";
}
  • Prints 0 to 4 (5 iterations)

  • If you wanted 0 to 5, this is an off-by-one error

Example: Extra Iteration

for ($i = 0; $i <= 5; $i++) {
echo $i . "<br>";
}
  • Prints 0 to 5 (6 iterations)

  • Sometimes developers expect 5 iterations, but the loop ran 6

How to Fix:

  • Carefully check whether you should use < or <=

  • Align the loop with the intended number of iterations

 

Performance Tips and Best Practices for PHP for Loops

The php for loop is a fundamental tool in PHP programming, but writing loops efficiently is just as important as writing them correctly. Optimizing loop performance and following best practices ensures your code runs faster, uses fewer resources, and is easier to maintain.

1. Optimizing Loop Conditions

The condition in a php for loop is evaluated on every iteration. For large loops, evaluating complex expressions repeatedly can slow down execution. Optimizing these conditions improves performance.

Example: Inefficient Loop

$numbers = range(1, 1000);

for ($i = 0; $i < count($numbers); $i++) {
echo $numbers[$i] . “<br>”;
}

  • count($numbers) is calculated on every iteration

  • For large arrays, this can significantly slow down the loop

Optimized Loop

$numbers = range(1, 1000);
$length = count($numbers); // Calculate once

for ($i = 0; $i < $length; $i++) {
echo $numbers[$i] . “<br>”;
}

  • count($numbers) is stored in a variable

  • The loop condition is evaluated quickly

Tip: Precompute values or use variables instead of calling functions repeatedly inside the loop.

2. Using the Correct Increment/Decrement

Simple and predictable increments make loops faster and reduce errors. Avoid unnecessary calculations in the increment section.

Example: Inefficient Increment

for ($i = 0; $i < 10; $i += 1*1) {
echo $i . "<br>";
}

Optimized Increment

for ($i = 0; $i < 10; $i++) {
echo $i . "<br>";
}
  • Simple $i++ is faster and easier to read

3. Minimizing Work Inside the Loop

Place calculations or operations that don’t change inside the loop before the loop starts.

Example: Inefficient Loop

for ($i = 0; $i < 100; $i++) {
$squareRoot = sqrt(100); // Recomputed every iteration
echo $squareRoot . "<br>";
}

Optimized Loop

$squareRoot = sqrt(100); // Compute once
for ($i = 0; $i < 100; $i++) {
echo $squareRoot . "<br>";
}

4. Best Practices for Clean and Readable Loops

Writing readable loops is as important as performance. Follow these practices:

  • Use meaningful variable names

    for ($index = 0; $index < $length; $index++) { ... }

    instead of

    for ($i = 0; $i < $n; $i++) { ... }
  • Avoid deep nesting – Nested loops are sometimes necessary, but keep nesting shallow for readability.

  • Comment complex logic – Explain why a loop exists or what it accomplishes.

  • Consistent formatting – Indent the loop body clearly and separate loop components for clarity.

Example: Clean and Optimized for Loop

$products = ["Laptop", "Phone", "Tablet", "Monitor"];
$totalProducts = count($products);

for ($index = 0; $index < $totalProducts; $index++) {
echo “Product #” . ($index + 1) . “: “ . $products[$index] . “<br>”;
}

  • Precomputed array length

  • Clear variable names

  • Clean formatting

 

Practical Examples and Exercises for PHP for Loops

Understanding the php for loop conceptually is important, but applying it to real-world scenarios and practicing with exercises will strengthen your skills. In this section, we will look at practical use cases and provide exercises with solutions.

Real-World Use Cases

  1. Generating Numbered Lists

$users = ["Alice", "Bob", "Charlie"];

for ($i = 0; $i < count($users); $i++) {
echo ($i + 1) . “. “ . $users[$i] . “<br>”;
}

Output:

1. Alice
2. Bob
3. Charlie

Use Case: Displaying ordered lists such as user lists, products, or items in a table.

  1. Multiplication Table

for ($i = 1; $i <= 10; $i++) {
echo "5 x $i = " . (5 * $i) . "<br>";
}

Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50

Use Case: Educational tools, quick calculations, or generating math tables dynamically.

  1. Displaying Even Numbers

for ($i = 2; $i <= 20; $i += 2) {
echo $i . "<br>";
}

Output: 2, 4, 6, …, 20
Use Case: Filtering numeric sequences, creating number-based patterns.

  1. Nested Loops for Patterns

for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo "*";
}
echo "<br>";
}

Output:

*
**
***
**
**
*****

Use Case: Creating visual patterns, reports, or layout structures.

Practice Exercises with Solutions

Exercise 1: Print Numbers from 10 to 1

Task: Use a php for loop to print numbers in reverse order.

Solution:

for ($i = 10; $i >= 1; $i--) {
echo $i . "<br>";
}

Exercise 2: Sum of Numbers from 1 to 50

Task: Calculate the sum of all numbers from 1 to 50 using a php for loop.

Solution:

$sum = 0;
for ($i = 1; $i <= 50; $i++) {
$sum += $i;
}
echo "Total Sum: " . $sum;

Exercise 3: Display Odd Numbers Between 1 and 20

Task: Print all odd numbers from 1 to 20.

Solution:

for ($i = 1; $i <= 20; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo $i . "<br>";
}

Exercise 4: Multiplication Table of Any Number

Task: Use a php for loop to print the multiplication table of 7 up to 10.

Solution:

for ($i = 1; $i <= 10; $i++) {
echo "7 x $i = " . (7 * $i) . "<br>";
}