PHP Basics in Tamil: Loops (for, while, do-while, foreach)

Part 1 – For Loop

  • For Loop – To Repeat no of Times.
  • Syntax:
<?php
for($i = 1; $i <= 5; $i++){
    echo "Number: $i <br>";
}
?>

  • Output: 1,2,3,4,5

Part 2 – While Loop

  • While Loop condition true இருக்கும் வரை repeat செய்யும்.
<?php
$i = 1;
while($i <= 5){
    echo "Number: $i <br>";
    $i++;
}
?>


Part 3 – Do-While Loop

  • Do-While Loop குறைந்தது ஒரு முறை code execute செய்யும்.
<?php
$i = 1;
do{
    echo "Number: $i <br>";
    $i++;
} while($i <= 5);
?>


Part 4 – Foreach Loop

  • Foreach Loop mainly arrays iterate செய்ய பயன்படும்.
<?php
$colors = array("Red","Green","Blue");
foreach($colors as $color){
    echo "Color: $color <br>";
}
?>


Part 5 – Real-life Example

  • Array values display
  • Table rows iterate
  • Invoice items repeat
<?php
$items = array("Pen"=>10,"Book"=>5,"Notebook"=>7);
foreach($items as $item => $qty){
    echo "$item quantity: $qty <br>";
}
?>