[PHP] Remove empty array elements with array_filter

Created on November 30, 2026

Call array_filter without a callback to remove values PHP treats as empty.

<?php

$values = ["apple", "", null, "banana", false, "orange"];

$filtered_values = array_filter($values);

var_dump($filtered_values);
array(3) {
  [0]=>
  string(5) "apple"
  [3]=>
  string(6) "banana"
  [5]=>
  string(6) "orange"
}

array_filter preserves the original keys. Wrap the result in array_values to assign consecutive indices starting at zero.

<?php

$values = ["apple", "", null, "banana", false, "orange"];

$filtered_values = array_values(array_filter($values));

var_dump($filtered_values);
array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(6) "orange"
}

Without a callback, this also removes 0, "0", and false, along with empty strings and null.

PHP