Home >Backend Development >PHP Tutorial >php foreach
In PHP development, we often iterate an array and modify the values of its elements. If we have experience in other languages, we are likely to make mistakes here.
Take java as an example, because I am still relatively familiar with java. In java, we iterate an array and modify its value. We will use the following method:
<span> </span>for(Object item : objectArray){ <span> </span>item.setAttribute('value'); <span> </span>}
foreach($arrays as $item){ $item->name = 'value'; } echo $arrays[0]->name;
After some debugging, I finally guessed whether the above code passed a value instead of a reference. So I went to the official website to check the documentation and found that this was actually the case, so I modified the code to look like this:
foreach($arrays as &$item){ $item->name = 'value'; } echo $arrays[0]->name;Or like this:
foreach($arrays as $key=>$item){ $arrays[$key]->name = 'value'; } echo $arrays[0]->name;The results of both methods are OK. Therefore, I feel that I should read more official documents. At first, I just went through it in general and started working on the project without really reading it thoroughly.
Reference materials:
PHP official website’s explanation of foreach: http://php.net/manual/en/control-structures.foreach.php
For more information, please follow the WeChat public account: Development and Life
The above introduces php foreach, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.