Remove empty array elements

Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:

foreach($linksArray as $link)
{
    if($link == '')
    {
        unset($link);
    }
}
print_r($linksArray);

But it doesn't work, $linksArray still has empty elements. I have also tried doing it with the empty() function but the outcome is the same.


As you're 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 ie exact string '0' , you will need a custom callback:

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

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

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);

$linksArray = array_filter($linksArray);

"If no callback is supplied, all entries of input equal to FALSE will be removed." -- http://php.net/manual/en/function.array-filter.php

链接地址: http://www.djcxy.com/p/75178.html

上一篇: .Any()的C#6空条件运算符检查?

下一篇: 删除空的数组元素