-1

I have created an associative array

$prijs = array (
    "Black & Decker Accuboormachine" => 148.85,
    "Bosch Boorhamer" => 103.97,
    "Makita Accuschroefmachine" => 199.20,
    "Makita Klopboormachine" => 76.00,
    "Metabo Klopboor" => 119.00        
);

Now I have to add a value to the array and I would like to use a function for this.

function itemToevoegen($array, $key, $value){
    $array[$key] = $value;
}

Then I call the function:

itemToevoegen($prijs, "Bosch GBH 18 V-LI", 412.37);

I have tried this without putting the array name in the input parameters but that does not work either.

=================== EDIT ===================== While typing this I thought I had to return the value, but that does not give me the desired result either.

function itemToevoegen($array, $key, $value){
    return $array[$key] = $value;
}

Could someone help me with this and tell me what I am missing here?

Thanks in advance.

2 Answers 2

2

Two options:

Passing by reference

You can pass a variable by reference to a function so the function can modify the variable.

function itemToevoegen(&$array, $key, $value){
    $array[$key] = $value;
}

or return array back and set new value

function itemToevoegen($array, $key, $value){
    $array[$key] = $value;
    return $array;
}

$prijs = itemToevoegen($prijs, "Bosch GBH 18 V-LI", 412.37);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer Rene.
1

Passing by Reference:

function itemToevoegen(&$array, $key, $value){
    $array[$key] = $value;
}

Pass by reference means that you can modify the variables that are seen by the caller. To do it, prepend an ampersand to the argument name in the function definition.

By default the function arguments are passed by value, so that if the value of the argument within the function is changed, it does not get changed outside of the function.

2 Comments

Thanks for the fast response @Leggendario. I have added the & and it works like a charm. Could you explain what this & is for in this context?
Pass by reference means that you can modify the variables that are seen by the caller. To do it, prepend an ampersand to the argument name in the function definition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.