for loop vs while loop vs foreach loop PHP

后端 未结 6 1729
迷失自我
迷失自我 2020-11-29 09:29

1st off I\'m new to PHP. I have been using for loop,while loop,foreach loop in scripts. I wonder

  • which one is better for performance?
  • what\'s the cri
6条回答
  •  日久生厌
    2020-11-29 09:57

    which one is better for performance?

    It doesn't matter.

    what's the criteria to select a loop?

    If you just need to walk through all the elements of an object or array, use foreach. Cases where you need for include

    • When you explicitly need to do things with the numeric index, for example:
    • when you need to use previous or next elements from within an iteration
    • when you need to change the counter during an iteration

    foreach is much more convenient because it doesn't require you to set up the counting, and can work its way through any kind of member - be it object properties or associative array elements (which a for won't catch). It's usually best for readability.

    which should be used when we loop inside another loop?

    Both are fine; in your demo case, foreach is the simplest way to go.

提交回复
热议问题