My PHP is quite basic when it comes to functions. I am trying to add a key and value pair to an already existing array via a function. 'Oranges' should also appear in the printed array. Can anyone explain what I am doing wrong?
function add_fruit($ar) {
$ar[] = 'oranges';
}
$fruits = [
'0' => 'apples',
'1' => 'pears',
'2' => 'bananas',
];
add_fruit($fruits);
print_r($fruits);
$aris passed to your function as a copy, you will not be changing the original outside of the function with this. Either pass the parameter by reference (careful, with the necessary destruction of the reference afterwards, to avoid unwanted side effects), or have your function return the modified array, and then call it as$fruits = add_fruit($fruits);