Quickly Removing Empty Array Elements in PHP

Comments

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.

1
$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

1
$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. You can see it below, where the indices are [1] and [3] and not [0] and [1].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$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:

1
2
3
4
5
6
7
8
$myArray = array( 0, 'red', '', 'blue' );
$myArray = array_filter( $myArray );
print_r( array_slice( $myArray, 0 ) );
Array
(
  [0] => 'red'
  [1] => 'blue'
)

I haven’t benchmarked it to see whether it is faster than a loop.

Comments