Bird
0
0

You want to sum values from an array where some elements are strings with numbers and others are booleans. Which PHP code correctly sums all values?

hard📝 Application Q8 of 15
PHP - Type Handling
You want to sum values from an array where some elements are strings with numbers and others are booleans. Which PHP code correctly sums all values?
$arr = ['4', true, '3 cats', false];
A$sum = 0; foreach ($arr as $v) { $sum += (bool)$v; } echo $sum;
B$sum = 0; foreach ($arr as $v) { $sum .= $v; } echo $sum;
C$sum = 0; foreach ($arr as $v) { $sum += $v; } echo $sum;
D$sum = 0; foreach ($arr as $v) { $sum .= (string)$v; } echo $sum;
Step-by-Step Solution
Solution:
  1. Step 1: Understand implicit type coercion in addition

    Using '+=' with mixed types converts values to numbers automatically.
  2. Step 2: Check each option

    A sums correctly using implicit conversion ('4'->4, true->1, '3 cats'->3, false->0 =8). B concatenates strings. C casts to bool (1+1+1+0=3 wrong). D concatenates after string cast. Only A works.
  3. Final Answer:

    $sum = 0; foreach ($arr as $v) { $sum += $v; } echo $sum; -> Option C
  4. Quick Check:

    Use '+=' for numeric sum with mixed types [OK]
Quick Trick: '+=' auto-converts mixed types to numbers in PHP [OK]
Common Mistakes:
  • Using '.=' for addition
  • Casting to bool
  • Concatenating after string cast

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes