What is better for or foreach in nested loops with checking various conditions?
foreach looks laconic, and for me seems to work faster. Give professional advice?

    3 answers 3

    It seems to me, on those dimensions of the array, where it will be noticeable, the actions inside the cycle on the brakes will eclipse the difference between the structures completely. Use what is more convenient.

     for(;;) //, ΠΊΠΎΠ³Π΄Π° трСбуСтся активная Ρ€Π°Π±ΠΎΡ‚Π° с индСксами foreach( as ) //, ΠΊΠΎΠ³Π΄Π° со значСниями, Π»ΠΈΠ±ΠΎ ΠΊΠΎΠ³Π΄Π° индСксы ассоциативныС array_walk() // для ΠΊΠΎΡ€Ρ€Π΅ΠΊΡ‚ΠΈΡ€ΠΎΠ²ΠΊΠΈ массива. 

      Do not think about small optimizations. Use what you think best reflects your thought. If you think "I want to go around all the elements," maybe foreach is the best choice.

      Optimize only if (1) your program is running too slowly, and (2) you have determined that this particular cycle creates a problem.

      "Pre-optimization is the source of all the trouble," as Grandpa Cnut said.

      • 2
        @VladD and I will repeat for the hundredth time - that optimization needs to be done from the very beginning, even when the code is spinning in my head. Over time, this will become a habit and save a lot of strength and nerves. Who likes to return to the old, long-forgotten code? Yes, no one. - lampa
      • @lampa: I can not agree on all 100%. The code should be clean and easy to understand. Compare the usual implementation of copying memory and Duff's device . Although the non-standard implementation provides some performance gain, I would not want to see such code in the normal body of the program. Another optimization option would be to manually inline all the functions - we lose the clarity of the code, but we win a few microseconds on the saved calls. And so on. - VladD
      • 2
        @lampa: and the code should be so good and crystal clear that it is easy to understand and fix it even after a year. Otherwise, this is still a bad code, and it must be rewritten. - VladD
      • one
        The severe battle of comments on the answer to the sacramental question: for vs foreach for a small number of elements. Abstracting from time to interpret php-code. - alexlz
      • one
        This is also a good idea about pre-optimization. - avp

      Usually for for index arrays, and foreach for associative.

      • And I thought that in php all arrays are associative. And where you can read about the index arrays (1). There the element with a character key is not exactly written? (2) - alexlz
      • one
        @alexlz well, I think so) In principle, an array of the form: `$ array = array (); $ array [] = 1; $ array [] = 2; `Can be considered an index. Through for working with him is much more convenient. - lampa