PHP Multiple Choice Questions on “For Loops – 1”.
1. What will be the output of the following PHP code?
-
-
$i = 0;
-
for ($i)
-
{ -
print $i;
-
} -
?>
a) 0
b) infinite loop
c) no output
d) error
Answer: d
Clarification: Wrong syntax for for loop.
2. What will be the output of the following PHP code?
-
-
$colors = array("red","green","blue","yellow");
-
foreach ($colors as $value)
-
{ -
echo "$value
"; -
} -
?>
a)
red green blue yellow
b) red
c) no output
d) error
Answer: a
Clarification: This runs a for loop for that array.
3. What will be the output of the following PHP code?
-
-
for ($x = 0; $x <= 10; $x++)
-
{ -
echo "The number is: $x
"; -
} -
?>
a)
The number is: 0 The number is: 1 The number is: 2 The number is: 3 The number is: 4 The number is: 5 The number is: 6 The number is: 7 The number is: 8 The number is: 9 The number is: 10
b) The number is: 0
c) no output
d) error
Answer: a
Clarification: This runs a for loop from 0 to 10.
4. What will be the output of the following PHP code?
-
-
for ($x = 0; $x <= 10; print ++$x)
-
{ -
print ++$x;
-
} -
?>
a) 123456789101112
b) 12345678910
c) 1234567891011
d) infinite loop
Answer: a
Clarification: The value of x is incremented and printed twice before checking,this last loop it prints 11 and 12.
5. What will be the output of the following PHP code?
-
-
for ($x = 1; $x < 10;++$x)
-
{ -
print "*t";
-
} -
?>
a) **********
b) *********
c) ***********
d) infinite loop
Answer: b
Clarification: Loop runs from 1 to 9 i.e 9 times.
6. What will be the output of the following PHP code?
-
-
for ($x = -1; $x < 10;--$x)
-
{ -
print $x;
-
} -
?>
a) 123456789101112
b) 12345678910
c) 1234567891011
d) infinite loop
Answer: d
Clarification: The value of x is decremented thus making it an infinite loop.
7. What will be the output of the following PHP code?
-
-
$x;
-
for ($x = -3; $x < -5; ++$x)
-
{ -
print ++$x;
-
} -
?>
a) -3-4-5
b) -3-4
c) infinite loop
d) no output
Answer: d
Clarification: The loop is not even entered as x is initially 0.
8. What will be the output of the following PHP code?
-
-
for ($i++; $i == 1; $i = 2)
-
print "In for loop ";
-
print "After loopn";
-
-
?>
a) In for loop
b) After for loop
c) In for loopAfter for loop
d) Infinite loop
Answer: c
Clarification: The loop runs only once as value of x is incremented.
9. What will be the output of the following PHP code?
-
-
for (1; $i == 1; $i = 2)
-
print "In for loop ";
-
print "After loopn";
-
?>
a) In for loop
b) After for loop
c) In for loopAfter for loop
d) Infinite loop
Answer: b
Clarification: The loop does not run as i initialized in check statement will be zero.
10. What will be the output of the following PHP code?
-
-
for ($i == 2; ++$i == $i; ++$i)
-
print "In for loop ";
-
print "After loopn";
-
?>
a) In for loopIn for loopIn for loopIn for loop……infinitely
b) After for loopAfter for loopAfter for loop……..infinitely
c) In for loopAfter for loopIn for loopAfter for loopIn for loopAfter for loop…..infinitely
d) After for loop
