Bird
0
0

Consider this PHP code snippet:

medium📝 Debug Q14 of 15
PHP - Type Handling
Consider this PHP code snippet:
$x = '5 cats';
$y = 3;
$result = $x - $y;
echo $result;

Why might this code produce an unexpected result?
APHP converts '5 cats' to 5, so 5 - 3 = 2, which might be unexpected if you expect string behavior.
BBecause subtraction is not defined for strings, it causes a fatal error.
CThe variable $result will be the string '5 cats3' due to concatenation.
DPHP treats both as strings and outputs '5 cats3'.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze subtraction with string and integer

    PHP converts the string '5 cats' to the number 5 for arithmetic operations.
  2. Step 2: Calculate the subtraction

    5 - 3 equals 2, so $result is 2, which may surprise if expecting string concatenation or error.
  3. Final Answer:

    PHP converts '5 cats' to 5, so result is 2 -> Option A
  4. Quick Check:

    '5 cats' - 3 = 2 [OK]
Quick Trick: Subtraction forces string to number conversion [OK]
Common Mistakes:
  • Expecting string concatenation with - operator
  • Thinking it causes an error
  • Assuming result is a string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes