Bird
0
0

Given the array $arr = ['1', '2', '3.5', 'true', 'false', '0'];, which code snippet correctly converts all elements to their proper types using settype?

hard📝 Application Q15 of 15
PHP - Type Handling
Given the array $arr = ['1', '2', '3.5', 'true', 'false', '0'];, which code snippet correctly converts all elements to their proper types using settype?
Aforeach ($arr as &$v) { if ($v === 'true' || $v === 'false') settype($v, 'bool'); elseif (strpos($v, '.') !== false) settype($v, 'float'); else settype($v, 'int'); }
Bforeach ($arr as &$v) { if (is_numeric($v)) settype($v, 'float'); else settype($v, 'bool'); }
Cforeach ($arr as &$v) { settype($v, 'int'); }
Dforeach ($arr as &$v) { settype($v, 'string'); }
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the array elements and desired types

    Elements are strings representing integers, floats, and booleans. We want to convert 'true'/'false' to bool, numbers with '.' to float, others to int.
  2. Step 2: Evaluate each option's logic

    foreach ($arr as &$v) { settype($v, 'int'); } converts all to int, losing floats and booleans. foreach ($arr as &$v) { if (is_numeric($v)) settype($v, 'float'); else settype($v, 'bool'); } converts all numeric to float, which is incorrect for integers. foreach ($arr as &$v) { if ($v === 'true' || $v === 'false') settype($v, 'bool'); elseif (strpos($v, '.') !== false) settype($v, 'float'); else settype($v, 'int'); } checks for 'true'/'false' strings to bool, floats by '.', else int - this matches the requirement. foreach ($arr as &$v) { settype($v, 'string'); } converts all to string, no type change.
  3. Final Answer:

    foreach ($arr as &$v) { if ($v === 'true' || $v === 'false') settype($v, 'bool'); elseif (strpos($v, '.') !== false) settype($v, 'float'); else settype($v, 'int'); } -> Option A
  4. Quick Check:

    Check string values carefully for correct type conversion = C [OK]
Quick Trick: Check string content to decide type before settype [OK]
Common Mistakes:
  • Converting all to int losing floats and booleans
  • Using is_numeric alone without checking for booleans
  • Forgetting to handle 'true' and 'false' strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes