PHP › Arrays in PHP
How does PHP handle array copying behavior, and when do arrays actually get passed by reference instead of by value?
AdvancedAnswer
PHP arrays are value types by default, meaning assigning an array to a new variable or passing it into a function creates an independent copy, so changes to the copy do not affect the original, but you can explicitly pass an array by reference using an ampersand in a function's parameter definition, meaning changes made inside that function directly affect the original array passed in, which is an important distinction to understand to avoid unexpected bugs.
function addItem(array &$cart, string $item) {
$cart[] = $item;
}
$cart = ['apple'];
addItem($cart, 'banana');
print_r($cart);Real-world example A shopping cart function is intentionally designed to accept the cart array by reference, so that adding an item inside the function directly updates the original cart variable used elsewhere in the application, avoiding the need to return and reassign the array manually.