Home > Backend Development > PHP Tutorial > How to change the original array while adding & traversing to foreach in PHP

How to change the original array while adding & traversing to foreach in PHP

小云云
Release: 2023-03-20 17:06:01
Original
2132 people have browsed it

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);//这样可以得到我们想要的数组
      }
Copy after login

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前面加了'&'所以原数组就直接改变了
}
Copy after login


Related recommendations:

Usage and difference between for loop and foreach loop in PHP

PHP How to use foreach to convert arrays

How to understand the difference between the for and foreach loop structures in PHP to traverse 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template