Bird
0
0

What happens if you modify the array inside a foreach loop in PHP? For example:

hard📝 Conceptual Q10 of 15
PHP - Loops
What happens if you modify the array inside a foreach loop in PHP? For example:
$arr = [1, 2, 3];
foreach ($arr as &$val) {
  $val *= 2;
}
print_r($arr);
AThe original array values are doubled because foreach uses references.
BThe array remains unchanged because foreach copies values.
CThe code causes a syntax error due to & in foreach.
DOnly the last element is doubled.
Step-by-Step Solution
Solution:
  1. Step 1: Understand foreach with reference

    Using & before the loop variable means it references original array elements.
  2. Step 2: Effect of modifying referenced values

    Changes inside the loop affect the original array, doubling each value.
  3. Final Answer:

    The original array values are doubled because foreach uses references. -> Option A
  4. Quick Check:

    Using & in foreach modifies original array [OK]
Quick Trick: Use & to modify original array elements inside foreach [OK]
Common Mistakes:
  • Thinking foreach copies values
  • Assuming syntax error with &
  • Believing only last element changes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes