删除空数组元素 [英] Remove empty array elements

查看:29
本文介绍了删除空数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据用户提交的内容,我的数组中的某些元素是空字符串.我需要删除这些元素.我有这个:

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

但它不起作用.$linksArray 仍然有空元素.我也试过用 empty() 函数来做,但结果是一样的.

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.

推荐答案

当你处理一个字符串数组时,你可以简单地使用 array_filter(),它可以方便地为您处理所有这些:

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

请记住,如果没有提供回调,则数组的所有条目都等于 FALSE(请参阅 转换为布尔值) 将被删除.因此,如果您需要保留元素,即精确字符串 '0',您将需要一个自定义回调:

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 !== "";')));

这篇关于删除空数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆