Bird
0
0

You have an array $data = ['1', '2', '3abc', '0', 'true', 'false'];. How can you convert all elements to integers using settype inside a foreach loop that declares both a key and value variable?

hard📝 Application Q8 of 15
PHP - Type Handling
You have an array $data = ['1', '2', '3abc', '0', 'true', 'false'];. How can you convert all elements to integers using settype inside a foreach loop that declares both a key and value variable?
Aforeach ($data as &$value) { settype($value, 'int'); }
Bforeach ($data as $value) { settype($value, 'int'); }
Cforeach ($data as $key => &$value) { settype($value, 'int'); }
Dforeach ($data as $key => $value) { settype($value, 'int'); }
Step-by-Step Solution
Solution:
  1. Step 1: Understand passing by reference

    To modify array elements inside a loop, use reference (&$value) to change original values.
  2. Step 2: Check options

    foreach ($data as $key => &$value) { settype($value, 'int'); } uses reference and key, allowing settype to modify each element correctly.
  3. Final Answer:

    foreach ($data as $key => &$value) { settype($value, 'int'); } -> Option C
  4. Quick Check:

    Use references to modify array elements with settype [OK]
Quick Trick: Use & to modify array elements inside foreach [OK]
Common Mistakes:
  • Not using reference, so original array unchanged
  • Modifying copy of value instead of original
  • Using wrong loop syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes