Add a key and value into an array via function

Viewed 44

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);
3 Answers

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);

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 )

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

Your code should look like this:

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