What is the best practice for passing arrays to functions in PHP to avoid unnecessary memory usage?
When passing arrays to functions in PHP, it's best to pass them by reference using the `&` symbol to avoid unnecessary memory usage. This way, the function operates directly on the original array without creating a copy. This can be especially important when dealing with large arrays to improve performance and reduce memory overhead.
// Passing an array by reference to avoid unnecessary memory usage
function processArray(&$arr) {
// Modify the original array directly
foreach ($arr as $key => $value) {
$arr[$key] = $value * 2;
}
}
// Example usage
$data = [1, 2, 3, 4, 5];
processArray($data);
print_r($data); // Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 )