Can we use for loop for array in php?

PHP, just like most other programming languages has multiple ways to loop through arrays. The most popular ways to do it usually is with a while, for and foreach operator, but, believe it or not, there are more ways to do it with PHP. In this article, I will walk-through each possibility for reading arrays whilst looping.

1. While Loop

The while loop is probably the most popular because of the recognizable and meaningful name. I always like to think of the while loop as the following.

Whilst something is true, the loop will continue looping or vice versa.

This method is commonly used when working with database results in the style of arrays but at the same time, are a completely feasible way to read non-database result-arrays.

With a plain array, we can create a true or false value depending on if the array has been looped over till the end. To achieve this, another variable must be created, an index indicator variable that does two things, allows us to pick out each of the values in the array as well as instructing the while loop when to stop. It’s somewhat very similar to how a for loop works, which we will touch on later.

PHP Code

        $CodeWallTutorialArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread", "RedSauce"];
        $arrayLength = count[$CodeWallTutorialArray];
        
        $i = 0;
        while [$i < $arrayLength]
        {
            echo $CodeWallTutorialArray[$i] ."
"; $i++; }

Output

Eggs
Bacon
HashBrowns
Beans
Bread
RedSauce

2. For Loop

As demonstrated in the last section for while loops, you will see how similar the for loop is. It uses the very same concept for looping and picking out information from the array. Three parameters are needed for the for loop and they are as follows –

  1. An initial counter set to a certain value, usually zero.
  2. A Boolean test, usually involving the initial counter.
  3. A counter increment eg: counter++.

The start of the loop will always look similar to the following –

for [$i = 0; $i < count[$arr]; $i++]

What’s really important to note here is that you must use semi-colons after the first two parameters otherwise the code will throw an exception. Also, there is no need to increment the counter within the loop, as the for operator does this for you. Let’s put this loop into action in the following PHP.

PHP Code

        $CodeWallTutorialArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread", "RedSauce"];

        for [$i = 0; $i < count[$CodeWallTutorialArray]; $i++]  {
            echo $CodeWallTutorialArray[$i] ."
"; }

Output

Eggs
Bacon
HashBrowns
Beans
Bread
RedSauce

3. Foreach Loop

This type of loop is my personal favorite way to read arrays, there is no need for a boolean test, just simply pass in the array and do what you want with it. It’s both easy to use, understand and comes in handy for many use-cases. There isn’t a mandatory rule to use a numeric index to pick out data values, the foreach loop essentially rids this concept for you. Let’s see it in action –

PHP Code

       $foodArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread"];

        foreach [$foodArray as $food]  {
            echo $food ."
"; }

Output

Eggs
Bacon
HashBrowns
Beans
Bread

As you can see within the code example, there is much less fluff in terms of code. And, if you name your variables well, the code will make a lot more sense than other looping methods.

4. Do While Loop

You could almost say the do while loop is pretty scarce among PHP code, I personally rarely use it and similarly rarely see it from other peoples code neither. It’s essentially a longer or code-bulkier way of executing a while loop, which in a way, is pretty pointless. At the same time, it’s arguably more readable, but ultimately, it all comes down to preference.

With the do while loop, you will need to create a test within the while operator, just as you would in a pure while loop case.

PHP Code

       $foodArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread"];
        $i = 0;
        
        do {
            echo $foodArray[$i] . "
"; $i++; } while [$i < count[$foodArray]];

Output

Eggs
Bacon
HashBrowns
Beans
Bread

As you can see in the code, there is a need to create an increment index value that will work part as the test and part to access values from the array.

5. Array Iterator

Now, this is a slightly more advanced method of looping over arrays is called an ArrayIterator. It’s part of a wider class that exposes many accessible variables and functions. You are more likely to see this as part of PHP classes and heavily object-oriented projects. Again with this functionality, you may find it more preferable to others or vice versa. The documentation on this class is well worth eye-balling as you can see exactly what benefits it offers. For example, it instantly exposes a count of the array which is quick and useful.

PHP Code

        $programmingLanguagesArray = ["PHP", "C++", "C#", "Python", "Java"];
        
        $arrObject = new ArrayObject[$programmingLanguagesArray];
        $arrayIterator = $arrObject->getIterator[];

        while[ $arrayIterator->valid[] ]
        {
            echo $arrayIterator->current[] . "
"; $arrayIterator->next[]; }

Output

PHP
C++
C#
Python
Java

Function References

Here are the links to the documentation on each of the loops used within this article. Check them out as they are extremely informative and useful for bookmarking for reference later.

  • while
  • for
  • foreach
  • do while
  • ArrayIterator

Summary

With the demonstration of five ways to loop over arrays, you have the luxury of picking a preferred and truly personal way of doing things yourself. In some cases, one will perform better than the other with regards to what you need to achieve. I hope this comes in useful, now go do some cool stuff with some loops! Finally, feel free to copy any of the code in this article to use in your own projects or merely reference.

Can you use a for loop for an array?

We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array.

How do you iterate over an array in PHP?

6 ways to loop through an array in php.
while[expression]{ // Code to be executed }.
do { // Code to be executed } while[expression];.
for [expr1; expr2; expr3] { //Code to be executed }.
array_walk[array|object &$array, callable $callback, mixed $arg = null]: bool..

Can we use for loop for associative array in PHP?

So as we can see in the example above, we can easily loop through indexed array using for loop. But for Associative Arrays we need to use ForEach loop.

Which loop works only on arrays in PHP?

The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Chủ Đề