Home > Backend Development > PHP Tutorial > Detailed explanation of the difference between for loop and foreach in PHP

Detailed explanation of the difference between for loop and foreach in PHP

黄舟
Release: 2023-03-06 12:42:01
Original
1476 people have browsed it

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 (m.sbmmt.com)!


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