Php for loop

The for loop of PHP is similar to that of the C language. It has three parameters. first parameter is used to initialize the variable value, second parameter is used to define the condition and third parameter is used to increase or decrease the variable value.

Syntax:-


for (start_expression; condition_expression; increment_or_decrement_expression)

Example1:- Suppose, You have a variable $x and that has value 1 and you increase the $x value until $x value will be 4.


<?php
for ($x = 1; $x < 5; $x++) {
print $x ."<br/>";
}
?>
1
2
3
4

Try it Yourself

Example2:- Suppose, You have a variable $x and that has a value 5 and you decrease the $x value until $x value will be 2


<?php
for ($x = 5; $x>1; $x--) {
print $x ."<br/>";
}
?>
5
4
3
2

Try it Yourself

Php for loop – Interview Questions

Q 1: What is a for loop in PHP?

Ans: It repeats code a fixed number of times.

Q 2: Syntax of for loop?

Ans: for ($i=0; $i<5; $i++) { }

Q 3: When should for loop be used?

Ans: When iteration count is known.

Q 4: Can for loops be nested?

Ans: Yes.

Q 5: Is the loop counter mandatory?

Ans: No, but recommended.

Php for loop – Objective Questions (MCQs)

Q1. for loop is ideal when the number of iterations is ______.






Q2. How many parts are in a for loop declaration?






Q3. Which part of the for loop executes only once?






Q4. Which keyword exits a loop immediately?






Q5. for loop executes the body ______ times when the condition is true.






Related Php for loop Topics