Master the for loop in PHP to execute code repeatedly with control. Explore syntax, practical examples, and best practices for efficient PHP programming.
for
Statement in PHPThe for
loop is one of the most commonly used loops in PHP. It lets you repeat a block of code a certain number of times. If youβve used for
loops in languages like C or JavaScript, PHPβs version will feel familiar.
for (initialization; condition; increment) {
// Code to be repeated
}
true
, the loop runs again. If itβs false
, the loop stops.π‘ All three parts are optional, but at least the semicolons (
;
) must be there.
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i <br>";
}
?>
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
for
loopfor ($i = 1; $i <= 10; $i++) {
echo $i;
}
for
loopfor ($i = 1; ; $i++) {
if ($i > 10) {
break; // Stop the loop manually
}
echo $i;
}
$i = 1;
for (; ; ) {
if ($i > 10) break;
echo $i;
$i++;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP For Loop</title>
</head>
<body>
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
</body>
</html>
for
loops when you know exactly how many times you want to run a block of code.false
.further reading: