Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to remove empty values from an array

Short answer

array_filter() without a second argument removes every "empty" value:

<?php
 
echo json_encode(array_values(array_filter(['a', '', null, 'b', false])));

Output:

["a","b"]

Keeping zero

Zero counts as empty too. To keep it, state the condition explicitly:

<?php
 
$values = [0, '', 5, null, '0'];
 
echo json_encode(array_values(array_filter($values, fn ($value) => $value !== '' && $value !== null)));

Output:

[0,5,"0"]

Strings of spaces

Trim the spaces first:

<?php
 
$lines = ['tea', '  ', 'coffee', ''];
 
echo json_encode(array_values(array_filter(array_map('trim', $lines))));

Output:

["tea","coffee"]

Functions used in this recipe

  • array_filter — Keeps the array elements that pass a test.
  • array_values — Returns the values of an array with keys numbered from zero.
  • trim — Removes whitespace and other characters from both ends of a string.

Thanks for reading!

Donate to the site — we work hard for you.