For loop tips & tricks with Php

PHP


Categories

JavaScript Design Patterns PHP jQuery MySQL Databases WordPress Algorithms HTML

Tipo IT - where your web applications live

Let us now look at a few examples of where and how to use For Loops in Php.

Create hashes with a Php For Loop

php-for-loop-tricks
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 count function 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:

Use variables instad of functions as arguments in a For Loop

php-for-loop-tricks
Sometimes not even experienced php web developers do not know that they can use For Loops in PHP for creating different listings without writing special functions for it. For example, we can iterate through letters or dates with one line of code with For Loops in-built functionality:

Creating a date list with a For Loop

php-for-loop-tricks

Creating a letter list with a For Loop

php-for-loop-tricks

For a final example we construct a function that uses a For Loop to iterate through a user list and add a unique password for each user in the array:

Creating passwords with a For Loop

php-for-loop-tricks
This was a brief introduction to PHP implementation of a for loop construct.

back to articles...