Wednesday, July 31, 2013

Quickly Removing Empty Array Elements in PHP

Different ways of removing empty array slots in PHP.

Removing empty array slots in PHP, leaving holes in the array.

A quick way to remove empty elements from an array is using array_filter without a callback function. This will also remove 0s (zeroes) though.

$myArray = array_filter( $myArray );

Alternatively, array_diff allows you to decide which elements to keep. The following example will only remove empty strings, but keep 0

$myArray = array_diff($myArray, array(''));

Removing empty array slots in PHP, and compacting the array
Both functions leave ‘gaps’ where the empty entries used to be:

$myArray = array( 0, 'red', '', 'blue');

print_r(array_filter($myArray));
Array
(
  [1] => 'red'
  [3] => 'blue'
)

print_r(array_diff($myArray, array('')));
Array
(
  [0] => 0
  [1] => 'red'
  [3] => 'blue'
)

array_slice can remove those gaps:

$myArray = array(0, 'red', '', 'blue');
$myArray = array_filter($myArray);
print_r(array_slice($myArray, 0));
Array
(
  [0] => 'red'
  [1] => 'blue'
)

see whether it is faster than a loop.

One more example

    $data = array(42, "foo", 96, "", 100.96, "php");
   
    // Filter each value of $data through the function is_numeric
    $numeric_data = array_filter($data, "is_numeric");
   
    // Re-key the array so the keys are sequential and numeric (starting at 0)
    $numeric_data = array_values($numeric_data);
   
    // Print out the new, filtered data
    print_r($numeric_data);

The output from above is:

Array
(
    [0] => 42
    [1] => 96
    [2] => 100.96
)