PHP Puzzles on “If-Else-If – 3”.
1. What will be the output of the following PHP code?
-
-
$x = 10;
-
$y = 5;
-
$z = 3;
-
if ($x / $y / $z)
-
print "hi";
-
else -
print "hello";
-
?>
a) hi
b) hello
c) error
d) no output
Answer: a
Clarification: In php division returns a float that is a non zero value thus evaluates to true.
2. What will be the output of the following PHP code?
-
-
if (!print "hi")
-
if (print "hello")
-
print "hi";
-
?>
a) hi
b) hihellohi
c) hihi
d) no output
Answer: a
Clarification: Print returns true and thus the first if statement also is not executed.
3. What will be the output of the following PHP code?
-
-
if (print "hi" - 1)
-
print "hello"
-
?>
a) hi
b) hihello
c) error
d) no output
Answer: c
Clarification: print returns true and when 1 is subtracted it is syntax error.
4. What will be the output of the following PHP code?
-
-
$x = 1;
-
if ($x--)
-
print "hi"
-
$x--;
-
else -
print "hello"
-
?>
a) hi
b) hello
c) error
d) no output
Answer: c
Clarification: The if statement has no brackets and it expects a else/else if after a if.
5. What will be the output of the following PHP code?
-
-
$a = 10;
-
$b = 11;
-
if ($a < ++$a || $b < ++$b)
-
print "hello";
-
else -
print "hi";
-
?>
a) hi
b) hello
c) error
d) no output
Answer: a
Clarification: The operator precedence of ++ is higher than <, thus the increment happens first and then compared.
6. What will be the output of the following PHP code?
-
-
$a = 2;
-
if ($a-- - --$a - $a)
-
print "hello";
-
else -
print "hi";
-
?>
a) hi
b) hello
c) error
d) no output
Answer: b
Clarification: Computing the expression in the if clause,it sums upto to 2 which is a positive value.
7. What will be the output of the following PHP code?
-
-
$a = 2;
-
if ($a-- - --$a - $a)
-
print "hello";
-
else -
print "hi";
-
?>
a) hi
b) hello
c) error
d) no output
Answer: b
Clarification: Computing the expression in the if clause, it sums upto to 2 which is a positive value.
8. What will be the output of the following PHP code?
-
-
$a = "hello";
-
if ($a.length)
-
print $a.length;
-
else -
print "hi";
-
?>
a) hellolength
b) 5
c) hi
d) error
Answer: a
Clarification: The . operator appends a string and returns true.
9. What will be the output of the following PHP code?
-
-
$a = "hello";
-
if (strlen($a))
-
print strlen($a);
-
else -
print "hi";
-
?>
a) hellolength
b) 5
c) hi
d) error
Answer: b
Clarification: The function strlen($a) gives the length of the string, 5, which is considered true.
10. What will be the output of the following PHP code?
-
-
$a = "1";
-
$b = "0";
-
if ((int)$a && $b)
-
print"hi";
-
else -
print "hello";
-
?>
a) hello
b) no output
c) hi
d) error
Answer: a
Clarification: The expression is evaluated with values contained in the string, even without typecasting.
To practice all Puzzles on PHP, here is complete set of 250+ Multiple Choice Questions and Answers on PHP.
