PHP Multiple Choice Questions on “Variables – 1”.
1. What will be the output of the following PHP code?
-
-
$x = 5;
-
$y = 10;
-
$z = "$x + $y";
-
echo "$z";
-
?>
a) 15
b) 10 + 5
c) $z
d) $x + $y
Answer: b
Clarification: Variable z will store 10 + 5 because 10 + 5 is given in double-quotes.
2. What will be the output of the following PHP code?
-
-
$x = 4;
-
$y = 3;
-
$z = 1;
-
echo "$x = $x + $y + $z";
-
?>
a) 4 = 4 + 3 + 1
b) 8
c) 8 = 4 + 3 +1
d) Error
Answer: a
Clarification: Again since the variables are inside double quotes we get this result.
3. What will be the output of the following PHP code?
-
-
$x = 4;
-
$y = 3
-
$z = 1;
-
$z = $z + $x + $y;
-
echo "$z";
-
?>
a) $z
b) 15
c) 8
d) 1
Answer: c
Clarification: Normal addition of variables x, y and z occurs and result of 8 will be displayed.
4. What will be the output of the following PHP code?
-
-
$x = 3.3;
-
$y = 2;
-
echo $x % $y;
-
?>
a) 0
b) 1
c) 2
d) Error
Answer: b
Clarification: % is the modulo operator. Unlike in C we can use it get reminder or floating point numbers in PHP.
5. What will be the output of the following PHP code?
-
-
$x = 10;
-
$y = 4;
-
$z = 3;
-
echo $x % $y % $z;
-
?>
a) 0
b) 1
c) 2
d) Error
Answer: c
Clarification: The expression is considered as ($x%$y)%z in this case (10%4)%3 which is 2.
6. What will be the output of the following PHP code?
-
-
$x = 10;
-
$y = 4;
-
$z = 3;
-
echo ($x % ($y) + $z);
-
?>
a) 5
b) 3
c) 0
d) 1
Answer: a
Clarification: The innermost bracket is evaluated first, since it covers only variable y it is as good as not using brackets.
7. What will be the output of the following PHP code?
-
-
$x = 30;
-
$y = 20;
-
$z = 10;
-
echo $x + $y - $z / ($z - $y);
-
?>
a) 41
b) -4
c) -5
d) 51
Answer: d
Clarification: First ($z – $y) is evaluated then -$z/($z – $y) is evaluated this results in 1 which is added to $x + $y therefore we get 51.
8. What will be the output of the following PHP code?
-
-
$x = -1;
-
$y = 1;
-
$z = $x * $y + $z;
-
echo $z;
-
?>
a) Undefined variable z
b) -1
c)
Undefined variable z -1
d) None of the mentioned
Answer: c
Clarification: Since the variable z is not defined it returns the error also it takes z as 0 and returns the value -1.
9. What will be the output of the following PHP code?
-
-
$x = 4;
-
$y = -3;
-
$z = 11;
-
echo 4 + $y * $z / $x;
-
?>
a) 4.25
b) 3.25
c) -3.25
d) -4.25
Answer: d
Clarification: First the * is evaluated then / followed by + therefore we can rewrite this expression as 4 +((- 3 * 11) / 4) which results in -4.25.
10. What will be the output of the following PHP code?
-
-
$x = 3.5;
-
$y = 2;
-
$z = 2;
-
echo $x / $y / $z;
-
?>
a) 1.75
b) 0.875
c) 3.5
d) Error
Answer: b
Clarification: First $x / $y is evaluated then this is divided by $z therefore we get 0.875.