Explanation of the difference between A for loop and foreach in PHP

Source: Internet
Author: User
This paper mainly introduces the difference between for loop and foreach in PHP, which has good reference value. Let's take a look at the little series.

The difference between A for loop and foreach

foreach relies on IEnumerable.

The first time var A in GetList () is called GetEnumerator returns the first object and assigns A,

The MoveNext is called after each subsequent execution of Var A in GetList (). Until the end of the loop.

The period getlist () method executes only once.

+ View Code

The For loop is positioned by subscript. LIST[3] equivalent to * (List + 3).

+ View Code

The or loop will call GetCount () to compare the length of each loop. While foreach does not consider the length, it only calls once GetList ().


The For loop efficiency is higher than foreach when the fixed length or length does not require calculation.

It is convenient to use foreach in the uncertain length, or when the calculation length has a performance loss.

And the object in the collection is locked when foreach. The period cannot be modified.

The above is the PHP for loop and the difference between foreach detailed content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.