Question:

There is an array a = array (there are many elements here). Pass through the array with the for (i=0; i<=count(a); i++) loop for (i=0; i<=count(a); i++) . Is it possible to speed up the cycle somehow?

Answer:

1) Move count (a) to a separate variable.

2) Read the array from the end as a for (i=count(a); i>=0; i--) loop for (i=count(a); i>=0; i--)

  1. It seems to me or in the error condition and at <= count (greater or equal) the loop will run forever?
  2. Why if running along the array from the end will be faster?
  • Why do you need to speed up looping iterations in PHP? Then after all this code needs to be supported. And the most obvious way to iterate through the array foreach ($arr as $v) {...} - tutankhamun

1 answer 1

It seems to me or in the error condition and at <= count (greater or equal) the loop will run forever?

in the first case, it is less or equal, in the second, the cycle will not last forever, since i still increases each iteration and, one way or another, the condition is fulfilled. The only problem here is that it will be executed 1 time more than necessary with access to the extra element.

Why if running along the array from the end will be faster?

Formally, it does not matter which way to pass the array from the beginning or the end. Question in checking the conditions. The i <= count condition is executed at each iteration, that is, the count function is executed each time. In the case of a pass from the end, count is executed once to assign the initial value i . If we take out len = count(a) before the loop, and write the condition i < len then the speed will be the same.