PHP online test on “Operators – 2”.
1. What will be the output of the following PHP code?
-
-
$i = 0;
-
while ($i = 10)
-
{ -
print "hi";
-
} -
print "hello";
-
?>
a) hello
b) infinite loop
c) hihello
d) error
Answer: b
Clarification: While condition always gives 1.
2. What will be the output of the following PHP code?
-
-
$i = "";
-
while ($i = 10)
-
{ -
print "hi";
-
} -
print "hello";
-
?>
a) hello
b) infinite loop
c) hihello
d) error
Answer: b
Clarification: While condition always gives 1.
3. What will be the output of the following PHP code?
-
-
$i = 5;
-
while (--$i > 0)
-
{ -
$i++;
-
print $i;
-
print "hello";
-
} -
?>
a) 4hello4hello4hello4hello4hello…..infinite
b) 5hello5hello5hello5hello5hello…..infinite
c) no output
d) error
Answer: a
Clarification: i is decremented in the first while execution and then continuously incremented back.
4. What will be the output of the following PHP code?
-
-
$i = 5;
-
while (--$i > 0 && ++$i)
-
{ -
print $i;
-
} -
?>
a) 5
b) 555555555…infinitely
c) 54321
d) error
Answer: b
Clarification: As it is && operator it is being incremented and decremented continuously.
5. What will be the output of the following PHP code?
-
-
$i = 5;
-
while (--$i > 0 || ++$i)
-
{ -
print $i;
-
} -
?>
a) 54321111111….infinitely
b) 555555555…infinitely
c) 54321
d) 5
Answer: a
Clarification: As it is || operator the second expression is not evaluated till i becomes 1 then it goes into a loop.
6. What will be the output of the following PHP code?
-
-
$i = 0;
-
while(++$i || --$i)
-
{ -
print $i;
-
} -
?>
a) 1234567891011121314….infinitely
b) 01234567891011121314…infinitely
c) 1
d) 0
Answer: a
Clarification: As it is || operator the second expression is not evaluated and i is always incremented, in the first case to 1.
7. What will be the output of the following PHP code?
-
-
$i = 0;
-
while (++$i && --$i)
-
{ -
print $i;
-
} -
?>
a) 1234567891011121314….infinitely
b) 01234567891011121314…infinitely
c) no output
d) error
Answer: c
Clarification: The first condition itself fails thus the loop exits.
8. What will be the output of the following PHP code?
-
-
$i = 0;
-
while ((--$i > ++$i) - 1)
-
{ -
print $i;
-
} -
?>
a) 00000000000000000000….infinitely
b) -1-1-1-1-1-1-1-1-1-1…infinitely
c) no output
d) error
Answer: a
Clarification: (–$i > ++$i) evaluates to 0 but -1 makes it enters the loop and prints i which is 0.
9. What will be the output of the following PHP code?
-
-
$i = 2;
-
while (++$i)
-
{ -
while ($i --> 0)
-
print $i;
-
} -
?>
a) 210
b) 10
c) no output
d) infinite loop
Answer: a
Clarification: The loop ends when i becomes 0.
10. What will be the output of the following PHP code?
-
-
$i = 2;
-
while (++$i)
-
{ -
while (--$i > 0)
-
print $i;
-
} -
?>
a) 210
b) 10
c) no output
d) infinite loop
Answer: d
Clarification: The loop never ends as i is always incremented and then decremented.
To practice all areas of PHP for online tests,
