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:
我有一个空数组,我试图通过一个简单的PHP函数推送值。问题是在每次迭代中都没有保留这些值。这是一个例子:
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?
这只会打印一个空数组。而我希望看到的是添加到$ colors数组的值。有什么建议么?
1 个解决方案
#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);
#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);