How to parse an array in php

→ Are you a new visitor? Please visit the page guidance for new visitors ←

How to parse an array in php

I remember back when I first started programming that I was having a bit of hard time when parsing an array in any giving language (well only php or java at the time), its always like that, after you learn it, you always think its very simple. Well same is for me, I’m not trying to brag, but I will show 3 methods of parsing an array really quick in PHP. The logic is similar in any programming language, be it php, perl, python, c, c++ etc., the logic is the same, but the syntax may be slightly different. So yeah, straight to the point, how to parse an array in php.

1. Loop through array using foreach

This is the simplest method there is and its also really fast. I’ll give you two examples for two arrays, one is a normal array and one is associative array.

The above will return each element at a time on each line. Now for associative arrays, this is almost the same.

This will print key1 – elem_1 on each line. And that is foreach method to loop through the array.

2. Loop through array using for

Using this method is a bit different, this works by iterating through the array keys. The logic here is that you declare a variable that is equal to zero (the first array key) and then you increment the variable by one on each iteration until you reach the total number of elements in the array. An example is bellow:

The above is similar to the first foreach method, it will print each element on each line.

3. Loop through array using while

This method is similar to the previous one, for, has the same principle to increment a variable until you reach the total number of elements from the array. The associative array part though is a bit different. Bellow you have the examples:

So its really similar to the previous method, now the associative array, as I said, it is slightly different:

This will print the output similar to the first method, foreach, key1 – elem_1. And that is how you parse any given array. Now the method selected doesn’t really matter, but foreach and while appear to be used the most as I’ve seen.

    • Well is true that you can use the iterator class, but implementing it is not so straight forward like the basic 3 loop methods and you also need to use one of the loop methods above if I’m not wrong.

  • Pingback: How to make a jQuery ajax call -

  • Matiss
    • Hello Matiss and thanks for checking. Indeed array_walk may also be a simple method, but not that straight forward either, for eg. you have the bellow:

      Basically all the parsing you do it in the function you call. Again, thanks for pointing this out!

Request an article ←