what are the difference between for loop & for each loop in php

前端 未结 8 1908
庸人自扰
庸人自扰 2021-01-04 09:24

What are the differences between the for loop and the foreach loop in PHP?

相关标签:
8条回答
  • 2021-01-04 10:23

    It should be pretty simple

    foreach abstracts away some of the complexity and is usually easier. I use this whenever I don't need to know the numerical index of the array or $key => $value won't provide me with it.

    for is the older C style where you must first perform a count() so you know how many iterations the loop requires. It is useful when you need to know the index, or to count backwards or step through in different groups.

    0 讨论(0)
  • 2021-01-04 10:29

    A "for" loop gives you an incrementing number (in its most common use) which you can use any way you like.

    "foreach" is a special construct made for looking at successive members of an array.

    As an example, you can use a "for" loop to create something that does what "foreach" does. But foreach does that with less required code.

    0 讨论(0)
提交回复
热议问题