2

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);
user1444027
  • 4,163
  • 7
  • 24
  • 34
  • 2
    `$ar` is 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);` – CBroe Feb 12 '21 at 10:20

3 Answers3

3

You can pass it by reference with the code you have just adding & to the param:

function add_fruit(&$ar) {
    $ar[] = 'oranges';
}

$fruits = [
    '0' => 'apples',
    '1' => 'pears',
    '2' => 'bananas',
];

add_fruit($fruits);

print_r($fruits);

The other option would be to return the modified array, doing something like this:

function add_fruit($ar) {
    $ar[] = 'oranges';
    return $ar;
}

$fruits = [
    '0' => 'apples',
    '1' => 'pears',
    '2' => 'bananas',
];

$fruits = add_fruit($fruits);

print_r($fruits);
Brugui
  • 478
  • 6
  • 14
2

You can also use array_push if you want to add multiple item, for single item better to use $array[] =

function add_fruit($ar) {
    array_push($ar, "oranges");
    return $ar;
}

$fruits = [
    '0' => 'apples',
    '1' => 'pears',
    '2' => 'bananas',
];

$fruits  = add_fruit($fruits);

print_r($fruits);

Result would be:

Array ( [0] => apples [1] => pears [2] => bananas [3] => oranges )

Devsi Odedra
  • 4,610
  • 1
  • 18
  • 29
1

You need to pass the parameter By Reference (see Passing by Reference)

Your code should look like this:

function add_fruit(&$ar) {
    $ar[] = 'oranges';
}
Gowire
  • 711
  • 3
  • 20