For loop tips and tricks with Php
For loop examples with PhpIn this article, we will look at a few use-case scenarios with a for loop construct in PHP. Sometimes, due to using different frameworks, developers forget about the building blocks of coding and how useful those elements can be in creating different scenarios in our app. Let us now look at a few examples of where and how to use for loop in Php.
We can use for loops to iterate through multidimensional arrays, and use
$ivariable with a little bit of elementary math, to extract only the first members of each sub-array. By changing the entry point and the size parameter ( that is the
$i=0part and the
$i < somethingpart ) of the loop, we can determine which sub-arrays we want to include. So for example, maybe we need all the first members of only top 3 sub-arrays, or the low 3 sub-arrays. For example, if we set
$i=2, first two sub-arrays will be left out, since indexes 0 and 1 will be left out.
Extract all first members of sub-arrays in a multidimensional array with a for loopAnd the result is:
Ok, I admit, this is not all that interesting. We could just insert the index instead of
$i-$ipart, but that would not be dynamic thinking. And it is important to think dynamically, because for example, we might want to do this next:
Do you see what we did? We added the
$i += 1part. So now we skip the step from within the loop and we extract only even sub-arrays. Now the result is:
Create hashes with a php for loopWe can create hashes using a for loop:
Since array size in this example is fetched on every iteration this code can be very slow at execution. What we should do, is optimize this loop by using an intermediate variable to store the size of the array instead of repeatedly calling the
countfunction which in turn makes the execution slower. We should always have this practice in mind if we use for loops.
So now previous example should look like this: