If I want to change a certain value of the array and traverse it directly, the original array will not change. Here are two methods
1. We can combine the data when traversing and then array_push() the data Assign it to another new array like this:
$data=array(1,2,3,4); $newdata=array(); foreach($data as $k=>$v){ if($v==2) $v=666;//我们想把值等于2的改为666 这样的话在内部改变了$v但是$data还是没改变 array_push($newdata,$v);//这样可以得到我们想要的数组 }
2. We can add an & symbol in front of the traversed value so that the original array can be changed without using array_push()
$data=array(1,2,3,4); foreach($data as &$v){ if($v==2) $v=666;//因为$v前面加了'&'所以原数组就直接改变了 }
Related recommendations:
Usage and difference between for loop and foreach loop in PHP
PHP How to use foreach to convert arrays
The above is the detailed content of How to change the original array while adding & traversing to foreach in PHP. For more information, please follow other related articles on the PHP Chinese website!