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:53

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 it's 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');
查看更多
步步皆殇っ
3楼-- · 2018-12-31 04:53

If you are working with a numerical array and need to re-index the array after removing empty elements, use the array_values function:

array_values(array_filter($array));

Also see: PHP reindex array?

查看更多
旧时光的记忆
4楼-- · 2018-12-31 04:55
foreach($arr as $key => $val){
   if (empty($val)) unset($arr[$key];
}
查看更多
与君花间醉酒
5楼-- · 2018-12-31 04:56
$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

查看更多
妖精总统
6楼-- · 2018-12-31 04:58

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);
查看更多
时光乱了年华
7楼-- · 2018-12-31 04:59
    $myarray = array_filter($myarray, 'strlen');  //removes null values but leaves "0"
    $myarray = array_filter($myarray);            //removes all null values
查看更多
登录 后发表回答