Bird
0
0

What will be the output of this PHP code?

medium📝 Predict Output Q5 of 15
PHP - Variables and Data Types
What will be the output of this PHP code?
$str = '12 bananas';
$num = 8;
$result = $str - $num;
echo $result;
AError: unsupported operand types
B20
C12 bananas8
D4
Step-by-Step Solution
Solution:
  1. Step 1: Understand PHP type juggling

    PHP converts strings to numbers when used with arithmetic operators, parsing from the start until a non-numeric character.
  2. Step 2: Convert '12 bananas' to integer

    PHP reads '12' and stops at the space, so '12 bananas' becomes 12.
  3. Step 3: Perform subtraction

    12 - 8 equals 4.
  4. Final Answer:

    4 -> Option D
  5. Quick Check:

    Arithmetic with numeric strings converts them to numbers [OK]
Quick Trick: Strings convert to numbers until non-digit [OK]
Common Mistakes:
  • Assuming string concatenation instead of subtraction
  • Expecting an error due to mixed types
  • Thinking the entire string is converted to zero

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes