Junior — Middle
What will be the result if you pass an array to a function and modify it inside the function?
sobes.tech AI
Answer from AI
In PHP, arrays are passed to functions by value, meaning a copy of the array is created. If you modify the array inside the function, these changes will not affect the original array outside the function.
Example:
function modifyArray($arr) {
$arr[] = 'new element';
print_r($arr);
}
$original = ['element1', 'element2'];
modifyArray($original);
print_r($original);
The output will be:
Array
(
[0] => element1
[1] => element2
[2] => new element
)
Array
(
[0] => element1
[1] => element2
)
If you want to modify the original array inside the function, you need to pass it by reference using &:
function modifyArrayByReference(&$arr) {
$arr[] = 'new element';
}
$original = ['element1', 'element2'];
modifyArrayByReference($original);
print_r($original);
Now, the changes will be saved to the original array.