Bird
0
0

Consider this PHP code snippet:

medium📝 Debug Q14 of 15
PHP - Variables and Data Types
Consider this PHP code snippet:
$x = '10 apples';
$y = 5;
$z = $x + $y;
echo $z;

What is the issue and how to fix it?
ANo issue; output is 15.
BWarning due to non-numeric string; fix by extracting number before addition.
CSyntax error; fix by adding semicolon after $y.
DRuntime error; fix by casting $y to string.
Step-by-Step Solution
Solution:
  1. Step 1: Understand PHP's behavior with non-numeric strings in math

    PHP tries to convert '10 apples' to number; it extracts leading number 10 but may raise a warning if strict error reporting is on.
  2. Step 2: Identify the fix

    To avoid warnings, explicitly extract the numeric part (e.g., using intval) before addition.
  3. Final Answer:

    Warning due to non-numeric string; fix by extracting number before addition. -> Option B
  4. Quick Check:

    Non-numeric strings cause warnings in math = C [OK]
Quick Trick: Extract numbers from strings before math to avoid warnings [OK]
Common Mistakes:
  • Assuming no warnings with mixed strings
  • Confusing syntax errors with runtime warnings
  • Casting integers to strings unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes