A few days ago I was reviewing some of my old PHP projects and I realized that I was mainly using
do-while to iterate over array. And this got me thinking: if there are more compact and better ways to work with arrays, why am I still anchored in 2010?
Arrays in PHP
As you already know, an array in PHP can be defined using the extended notation with the keyword array:
or, since version 5.4, using square brackets
In addition, its possible to create associative arrays (or dictionaries) if we specify the key under which each value is:
Anonymous Functions in PHP
Another cool “new feature” in PHP is anonymous functions. Basically, these are unnamed functions and they are often used as callbacks. For instance, WordPress‘ filters and actions require a callback for each filter or action you use:
In the previous example, we create a function called
multisite_body_classes and use it as the callback of the
body_class filter. Whenever WordPress needs to apply the
body_class filter, the
multisite_body_classes function is called.
Well, this is how it’d look if we used an anonymous function:
and the function is now defined directly in the filter itself. Notice this is not recommended, as we usually want to be able to remove a certain filter/action, and we need to know the name of the function to do so:
Most Common Operations with Arrays and How to Write Them
Let’s take a look at some common scenarios we might face when working with arrays and how to deal with them using PHP native functions.
Filter Array Elements that Meet a Certain Condition
The first example I can think of is filtering the elements of an array that meet a certain condition. We used to do this by creating a variable to store the results (
$results) and then traversing all the elements of the array using
while. Then, for every element, we checked the condition using an
But this, in reality, is much simpler to perform. PHP has a function that allows us to exactly filter the values we want from an array, conveniently named
array_filter. Let’s see the previous example using this function:
This function takes as a second parameter a callback function that is invoked for each element of the original array. If the function returns
true, the element is included in the result. If not, it’s not included.
In this example there are a couple of things that are worth commenting on. On the one hand, the use of the keyword
use. In order to use a variable within an anonymous function we must explicitly indicate that our function has access to said using the
On the other hand, you should keep in mind that
array_filter maintains the keys of the array. This is especially useful for associative arrays:
but might be strange for non-associative arrays:
since the result might not have correlative indexes. To ensure that the result indices start at
0 and are correlated, use
Search for a Specific Value Within the Array
Another common example is that of finding the first element that meets a certain condition within the array. This is very similar to the previous case, but instead of having an array of results, we have a single
In this case, it’s enough to repeat the previous solution, but indicating that we want to recover the element that we have in position
Create an Equivalent Array with Modified Items
Let’s now talk about processing all the elements of the array to get a new array. For instance, imagine that we have a price list and we want to apply 21% VAT to all of them. How do we do it? Usually, we’d do something similar to this:
but we can use the
array_map function to get the same effect:
Process all Elements of the Array to Extract a Single Summary Value
Suppose you have a list of products a user purchased and you want to get the total price. The logical thing to do would be to define the variable
$total_price and iterate over all the products to add their price to your total:
Well, we have a function named
array_reduce that produces exactly the same effect:
with it, we basically specify the array on which we want to work, the accumulation function (which has as parameters the current item and the value that we have accumulated) and the initial value of said accumulator.
I’m so happy about Nelio Content that I will sound like a payed advocate… but here’s why you’ll love it: it works as promised, its auto-scheduling feature is top-notch, Nelio’s value for money is unmatched, and the support team feels like your own.
Some More Examples…
If we want to find filter out the elements in one array that appear in another element, we can use the function
array_diff which calculates the “difference” between the two:
To eliminate the duplicate values of an array, we have
To know if a value is in the array or not, we have
And a long etcetera that you should not miss!.
Now that WordPress has bumped the minimal version of PHP, it’s time to get up to speed with newer PHP versions and write better code, don’t you think?
Featured image by Laurent Naville on Unsplash.