← Back to Chapters

PHP For Loop

? PHP For Loop

? Quick Overview

The for loop in PHP is used when the number of iterations is known in advance. It is commonly used for counting, repeating tasks, and numerical operations.

? Key Concepts

  • Initialization sets the starting value
  • Condition controls how long the loop runs
  • Increment updates the loop counter

? Syntax / Theory

? View Code Example
// Basic PHP for loop syntax
for (initialization; condition; increment) {
    // code to be executed
}

? Code Example

? View Code Example
// Loop from 1 to 5 and print values
<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Number: $i<br>";
}
?>

? Live Output / Explanation

The loop starts at $i = 1, checks the condition $i <= 5, and prints each number until the condition becomes false.

? Interactive Loop Simulator

Adjust the parameters below to see how the PHP for loop logic changes and what the resulting output would look like.

 
Browser-Rendered Output:
 

? Use Cases

  • Generating number sequences
  • Displaying tables and lists
  • Repeating calculations
  • Index-based array processing

✅ Tips & Best Practices

  • Use for loops when iteration count is fixed
  • Prefer foreach for array readability
  • Keep conditions simple to avoid logic errors

? Try It Yourself

  • Create a PHP file named for_loop.php
  • Print numbers from 1 to 10 with their squares
  • Experiment with different increment values