How does foreach() work with arrays in PHP and why does it create a copy of the array element?

When using foreach() with arrays in PHP, it creates a copy of the array element rather than working directly on the original array. This means that any modifications made to the array element within the foreach loop will not affect the original array. To solve this issue and modify the original array within the loop, you can use a reference variable in the foreach loop.

$array = [1, 2, 3, 4, 5];

foreach ($array as &$value) {
    $value *= 2;
}

unset($value); // unset the reference variable

print_r($array);