php – Remove empty array elements

php – Remove empty array elements

As youre dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you:

print_r(array_filter($linksArray));

Keep in mind that if no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string 0, you will need a custom callback:

// PHP 7.4 and later
print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ));

// PHP 5.3 and later
print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ; }));

// PHP < 5.3
print_r(array_filter($linksArray, create_function($value, return $value !== ;)));

 

Note: If you need to reindex the array after removing the empty elements, use: $linksArray = array_values(array_filter($linksArray));

You can use array_filter to remove empty elements:

$emptyRemoved = array_filter($linksArray);

If you have (int) 0 in your array, you may use the following:

$emptyRemoved = remove_empty($linksArray);

function remove_empty($array) {
  return array_filter($array, _remove_empty_internal);
}

function _remove_empty_internal($value) {
  return !empty($value) || $value === 0;
}

EDIT: Maybe your elements are not empty per se but contain one or more spaces… You can use the following before using array_filter

$trimmedArray = array_map(trim, $linksArray);

php – Remove empty array elements

The most popular answer on this topic is absolutely INCORRECT.

Consider the following PHP script:

<?php
$arr = array(1, , 2, 3, 0);
// Incorrect:
print_r(array_filter($arr));
// Correct:
print_r(array_filter($arr, strlen));

Why is this? Because a string containing a single 0 character also evaluates to boolean false, so even though its not an empty string, it will still get filtered. That would be a bug.

Passing the built-in strlen function as the filtering function will work, because it returns a non-zero integer for a non-empty string, and a zero integer for an empty string. Non-zero integers always evaluate to true when converted to boolean, while zero integers always evaluate to false when converted to boolean.

So, the absolute, definitive, correct answer is:

$arr = array_filter($arr, strlen);

Leave a Reply

Your email address will not be published.