Conditionally add items to an array in PHP

In PHP, arrays are a fundamental data structure that allows you to store multiple values in a single variable. However, sometimes you need to add elements to an array based on certain conditions. This can be achieved easily using the spread operator (...).

The spread operator allows you to expand an array into individual elements. It can also be used to merge arrays, but in this case, we will focus on its ability to conditionally add elements to an array.

Let's take a look at this example:

$names = ['Alice', 'Bob', 'Eve'];

if ($condition) {
    array_push($names, 'Mallory');
}

Here, we start out with a list of names and based on $condition, we add Mallory to that list.

You can rewrite this into one single assignment using the spread operator:

$names = [
    'Alice',
    'Bob',
    'Eve',
    ...($condition ? ['Mallory'] : []),
];

Empty arrays are discarded, so you'll end up with the same list as in the previous example when $condition is false.

The spread operator can be a powerful tool when it comes to manipulating arrays in PHP. It allows you to easily conditionally add elements to an array, which can result in more concise and readable code.

Clicky