Loop, by Laurent Naville

A few days ago I was reviewing some of my old PHP projects and I realized that I was mainly using for, while, and 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?

In Nelio, we’re currently getting up to speed with JavaScript development, so I thought: why don’t we do the same with PHP? After all, WordPress is bumping up the minimum PHP version it supports…

Today I bring you some tricks to write code in PHP in a way more similar to what we see in JavaScript. It’s nothing new, it’s not complicated… but maybe it’s something you didn’t know about. Let’s start reviewing some important concepts for today’s post: PHP arrays and anonymous functions.

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 for, foreach, while. Then, for every element, we checked the condition using an if statement:

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 use keyword.

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 array_values:

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 $item:

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 0:

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.

Nelio A/B Testing

Native Tests for WordPress

Use your WordPress page editor to create variants and run powerful tests with just a few clicks. No coding skills required.

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 array_unique:

To know if a value is in the array or not, we have in_array:

And a long etcetera that you should not miss!.

In Summary

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

I have read and agree to the Nelio Software Privacy Policy

Your personal data will be located on SiteGround and will be treated by Nelio Software with the sole purpose of publishing this comment here. The legitimation is carried out through your express consent. Contact us to access, rectify, limit, or delete your data.