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;
foreach($arrays as $key=>$item){ $arrays[$key]->name = 'value'; } echo $arrays[0]->name;
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.