Remove empty array elements

2018-12-31 04:06发布

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.

25条回答
何处买醉
2楼-- · 2018-12-31 05:00

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 i.e. 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 !== ''; }));
查看更多
登录 后发表回答