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 04:36

You can just do

array_filter($array)

array_filter: "If no callback is supplied, all entries of input equal to FALSE will be removed." This means that elements with values NULL, 0, '0', '', FALSE, array() will be removed too.

The other option is doing

array_diff($array, array(''))

which will remove elements with values NULL, '' and FALSE.

Hope this helps :)

UPDATE

Here is an example.

$a = array(0, '0', NULL, FALSE, '', array());

var_dump(array_filter($a));
// array()

var_dump(array_diff($a, array(0))) // 0 / '0'
// array(NULL, FALSE, '', array());

var_dump(array_diff($a, array(NULL))) // NULL / FALSE / ''
// array(0, '0', array())

To sum up:

  • 0 or '0' will remove 0 and '0'
  • NULL, FALSE or '' will remove NULL, FALSE and ''
查看更多
栀子花@的思念
3楼-- · 2018-12-31 04:36

For multidimensional array

$data = array_map('array_filter', $data);
$data = array_filter($data);
查看更多
步步皆殇っ
4楼-- · 2018-12-31 04:37
$my = ("0"=>" ","1"=>"5","2"=>"6","3"=>" ");   

foreach ($my as $key => $value) {
    if (is_null($value)) unset($my[$key]);
}

foreach ($my as $key => $value) {
    echo   $key . ':' . $value . '<br>';
} 

output

1:5

2:6

查看更多
高级女魔头
5楼-- · 2018-12-31 04:38
$out_array = array_filter($input_array, function($item) 
{ 
    return !empty($item['key_of_array_to_check_whether_it_is_empty']); 
}
);
查看更多
孤独总比滥情好
6楼-- · 2018-12-31 04:39

Just one line : Update (thanks to @suther):

$array_without_empty_values = array_filter($array);
查看更多
看淡一切
7楼-- · 2018-12-31 04:40

Another one liner to remove empty ("" empty string) elements from your array.

$array = array_filter($array, create_function('$a','return $a!=="";'));

Note: This code deliberately keeps null, 0 and false elements.


Or maybe you want to trim your array elements first:

$array = array_filter($array, create_function('$a','return trim($a)!=="";'));

Note: This code also removes null and false elements.

查看更多
登录 后发表回答