Skip to content
PHP Logo

How does PHP handle parameter passing, especially in terms of copy-on-write behavior, when working with arrays in functions?

When passing arrays as parameters to functions in PHP, the default behavior is to pass them by value, which means a copy of the array is made. This can lead to memory inefficiency, especially when dealing with large arrays. To optimize this, PHP uses copy-on-write behavior, where the array is only copied if it is modified within the function. To ensure this behavior, use the `&` symbol before the parameter name in the function definition.

php
function modifyArray(&$arr) {
    // Modify the array
}

$arr = [1, 2, 3];
modifyArray($arr);