Consider the following PHP code snippet. What will it output?
<?php $result = 3 + 4 * 2 / (1 - 5) ** 2 ** 3; echo $result; ?>
Remember that exponentiation (**) is right-associative and has higher precedence than multiplication and division.
The expression evaluates the exponentiation first, then multiplication and division, and finally addition. The result is approximately 3.0001220703125.
What will this PHP code print?
<?php $a = true; $b = false; $c = false; $result = $a && $b || $c; echo (int)$result; ?>
Logical AND (&&) has higher precedence than logical OR (||).
The expression is evaluated as ($a && $b) || $c, which is (true && false) || false = false || false = false, so output is 0.
Examine the following PHP code. What error will it produce when run?
<?php $value = 5; if ($value > 3 && $value < 10 || $value = 0) { echo 'Valid'; } else { echo 'Invalid'; } ?>
Assignment (=) inside conditions can cause warnings if not grouped properly.
The assignment inside the condition is allowed but triggers a warning because it is ambiguous without parentheses. The expression evaluates with assignment having lower precedence than logical operators.
What will this PHP code print?
<?php $score = 85; $message = 'Result: ' . $score > 80 ? 'Pass' : 'Fail'; echo $message; ?>
Concatenation (.) has lower precedence than comparison (>) and ternary (?:).
The expression is parsed as ('Result: ' . $score) > 80 ? 'Pass' : 'Fail'. The concatenation results in a string, which when compared to 80 converts to 0, so 0 > 80 is false, so 'Fail' is chosen. But echo prints the boolean result of the comparison concatenation, which is 1 (true) or empty string (false). Actually, operator precedence causes unexpected behavior here, resulting in 'Result: 1'.
Analyze this PHP code and determine the final value of $x.
<?php $x = 2; $x *= $x + 3; echo $x; ?>
Remember that the right side of the *= operator is evaluated before multiplication.
The expression is evaluated as $x = $x * ($x + 3) = 2 * (2 + 3) = 2 * 5 = 10.