How to Conditionally Add Elements to an Array in PHP?

Using the Conditional if

You could simply use the if statement to add more elements to the array:

$array = [
   'a' => 'one',
   'b'  => 'two'
];

if (true) {
   $array['c'] = 'three';
}

/* output: Array(
    [a] => 'one'
    [b] => 'two'
    [c] => 'three'
) */

Using the Array Union Operator

The + (union) operator can be used to combine any number of arrays. The union operator appends all right-hand arrays to the left-hand array. Using this information, we could use a ternary operator to create an array with values we want if the condition is met, or an empty array if the condition is not met. This would result in an array that combines value of all arrays in the set. For example:

[2 => 'one'] + (true ? [5 => 'two'] : []) + (false ? [10 => 'three'] : []);

/* output: Array(
    [2] => 'one'
    [5] => 'two'
) */

When using the union operator, remember that for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Using array_merge()

Similar to the union operator, we could use array_merge() to merge elements of one or more arrays together where the values of each array are appended to the end of the previous one.

array_merge(
    [2 => 'one'],
    (true ? [5 => 'two'] : []),
    (false ? [10 => 'three'] : [])
);

/* output: Array(
    [0] => 'one'
    [1] => 'two'
) */
  • If the arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will NOT overwrite the original value, but will be appended instead.
  • Values in an array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. You can use the union operator instead to maintain the original numeric keys, or any other method.

Using array_filter()

If used without a callback function as the second argument, the array_filter() function removes all falsy values by default, which includes:

  • Boolean false
  • Integer, Float and String 0
  • Empty String
  • Empty array() or []
  • Object with zero member variables
  • NULL
  • SimpleXML objects created from empty tags

So with that information, we could use a ternary operator (shorthand if / else) to add a value to an array when a condition is met, and any falsy value when the condition is not met. We can then use array_filter() to remove the falsy value. For example:

$array = [
    (true ? 'one' : ''),
    (false ? 'two' : '')
];

array_filter($array);

/* output: Array(
    [0] => 'one'
) */

Please note that array_filter() preserves array keys.

In case, we wanted to allow some of the falsy values, we could simply supply a callback function as a second argument to array_filter(). If the callback function returns TRUE, the current value from array is returned into the resulting array, for example:

$array = [
    'a' => (false ? 'one' : ''),
    'b' => (false ? 'two' : null),
    'c' => (false ? 'three' : []),
    'd' => (false ? 'four' : 0)
];

// remove all NULL, FALSE and Empty Strings but 0 (zero) values
array_filter($array, 'strlen');

/* output: Array(
    [d] => 0
) */

// remove null values only
array_filter($array, function ($val) {
    return ! is_null($val);
});

/* output: Array(
    [a] => ''
    [c] => Array()
    [d] => 0
) */

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.