Friday, 13 July 2018

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 = 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:
array(2 => 'one') + ((true) ? array(5 => 'two') : array()) + ((false) ? array(10 => 'three') : array());

/* 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(
    array(2 => 'one'),
    ((true) ? array(5 => 'two') : array()), 
    ((false) ? array(10 => 'three') : array())
);

/* 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 = 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 = array(
    'a' => ((false) ? 'one' : ''), 
    'b' => ((false) ? 'two' : NULL), 
    'c' => ((false) ? 'three' : array()), 
    '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
) */

0 comments:

Post a Comment