Help more people learn by sharing this post!

PHP Arrays

This is an introduction to PHP arrays, so if you are new to the language or you just need a refresher you can get up to speed pretty fast.

This is how we initialize an empty array and add some elements to it:

Then we can see it’s contents using the print_r() function. You may want to put this between <pre> tags for better formatting.

Output:

Another useful operation with arrays is knowing how many elements it contains. For that we can use the count() function.

One thing worth noting about php arrays is that they behave like hash maps. Because arrays are just key/value pairs, we can add a new pair like this:

Now let’s see how we can iterate through arrays, using the foreach() function.

Looping through php arrays

If we also want the keys and not just the values, we can do this:

Output:

You can download the example code here:
https://gist.github.com/3801039

Array function reference: http://php.net/manual/en/ref.array.php