php foreach

WBOY
Release: 2016-07-28 08:30:20
Original
1222 people have browsed it

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>}
Copy after login

The above code is no problem, everything is as we expected Come. Until I got to PHP and was working on a small project these days, I found that using a method similar to the above to modify the value of an element did not work! The code used is as follows:
		foreach($arrays as $item){
			$item->name = 'value';	
		}
		echo $arrays[0]->name;
Copy after login

I found that the output was the one before modification!

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

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!