This article mainly introduces the difference between for loop and foreach in PHP, which has a good reference value. Let’s take a look with the editor below
The difference between for loop and foreach
foreach relies on IEnumerable.
The first time var a in GetList (), call GetEnumerator to return the first object and assign it to a,
In the future, MoveNext will be called every time var a in GetList() is executed. Until the end of the loop.
During GetList( ) method is executed only once.
+ View Code
The for loop is positioned by subscript. List[3] is equivalent to *(list + 3).
+ View Code
or Each loop will call GetCount() to compare the length. Foreach does not consider the length and only calls GetList() once.
Conclusion.
The for loop is more efficient than foreach when the length is fixed or the length does not need to be calculated.
When it is uncertain length, or when there is a performance loss in calculating the length, it is more convenient to use foreach.
And the objects in the collection will be locked during foreach. They cannot be modified during the period.
The above is a detailed explanation of the difference between for loop and foreach in PHP. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!