0

I have an empty array that I am trying to push a value to via a simple php function. The problem is that within each iteration the values are not being retained. Here is an example:

function addColors($arrayValues, $arrayToUpdate){
    $arrayToUpdate[]=$arrayValues;
}

$colors = array();
$newColors= array("red", "blue", "yellow");

foreach($newColors as $newColor){
    addColors($newColor, $colors);
}

echo "<pre>".print_r($colors, true)."</pre>";

This will just print an empty array. Whereas what I would like to see are the values being added to the $colors array. Any suggestions?

2
  • Add & to $arrayToUpdate and $newColor in function definitions to keep it as reference. Commented Jun 13, 2017 at 15:35
  • Not quite sure what you mean, but perhaps you just need to pass the array by reference? function addColors($arrayValues, &$arrayToUpdate){ Commented Jun 13, 2017 at 15:35

1 Answer 1

2

You either need to return the new array and assign the returned array in the loop:

function addColors($arrayValues, $arrayToUpdate){
    $arrayToUpdate[]=$arrayValues;
    return $arrayToUpdate;
}

foreach($newColors as $newColor){
    $colors = addColors($newColor, $colors);
}

Or to do it the way you have it, pass the variable that needs to be updated as a reference; notice the &. This is my recommendation:

function addColors($arrayValues, &$arrayToUpdate){
    $arrayToUpdate[]=$arrayValues;
}

foreach($newColors as $newColor){
    addColors($newColor, $colors);
}

Though in this simple example I wouldn't use a function:

foreach($newColors as $newColor){
    $colors[] = $newColor;
}

Also, there is already a function that does this, though the arguments are in a different order:

array_push($colors, $newColor);

Even simpler without the loop:

$colors = array_merge($colors, $newColors);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.