How to Remove Empty Elements from PHP Array

0
1298

earlphpRemoving empty elements from a PHP array can be a very confusing task. Fortunately there are a few quick functions we can use to achive this, lets these methods.

Example 1: array_filter() function without callback

<?php
$sample = array(
 0 => 'foo',
 1 => false,
 2 => -1,
 3 => null,
 4 => '',
 5 => 0
);

var_dump(array_filter($sample));
?>
Output:
array (size=2)
  0 => string 'foo' (length=3)
  2 => int -1

As you can see from the above output, unless you have a good knowledge about what data will be in the array and exactly what you want to preserve, using array_filter() although generally most common method, may end up giving some iffy results. Also note that the resulting array indexes are not sequential.

Example 2: array_diff() function

Using array_diff() we can specify using an array as the second parameter, a list of elements we want removed. This is a sneaky but effective way of achieving out task by essentially subtracting elements from the second array from the first. Lets look at a few examples to make sense of this.

The same $sample variable will be used for all examples.

<?php
$sample = array(
    0 => 'foo',
    1 => false,
    2 => -1,
    3 => null,
    4 => '',
    5 => 0
);

var_dump(array_diff($sample, array('')));
?>
Output:
array (size=3)
  0 => string 'foo' (length=3)
  2 => int -1
  5 => int 0

LEAVE A REPLY

Please enter your comment!
Please enter your name here