In almost any programming language, it’s almost impossible to find a useful script which does not make use of arrays to store data. Arrays are particularly important because they allow coders to group variables and store them under one central structure. In PHP, Arrays are simply ordered maps. In other words, each value is associated with a key that you can choose to specify when creating your Array.

Below, you will find 5 examples of problems we often come across when dealing with arrays.

I want to order a multi-dimensional array by a value…

I would like to order this array by the date joined. How exactly can I achieve this? Although there are definitely multiple ways to do this, the simplest way I’ve found to do this is by using the array_multisort function. To do this, we need to create a separate array which stores the field we want to use to order.

I want to create a separate array that only includes members who joined on 2011-02-04…

I want to extract an array out of that which includes members who joined on 2011-02-04. To do that, we will create a function that would accept one element of this array and return whether the member was added on that date or not:

Note the we added to the parameter which basically passes the variable by reference. This allows the function to change the actual value, rather than create a copy of it. With that done, we simply need to run the following function:

A Summary

There are multiple ways to do the things we did above, including looping through the array and manipulating the data manually. However, it’s always a good idea to make use of PHP’s in-built array functions which allow you to re-use your code and achieve your objectives in less lines.

Any more tips? Are you aware of a better way to complete the tasks above? Let us know below!