php 删除空数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3654295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:34:28  来源:igfitidea点击:

Remove empty array elements

phparraysstring

提问by Will

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. $linksArraystill has empty elements. I have also tried doing it with the empty()function, but the outcome is the same.

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

回答by BoltClock

As you're dealing with an array of strings, you can simply use array_filter(), which conveniently handles all this for you:

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

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:

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

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

回答by Andrew Moore

You can use array_filterto remove empty elements:

您可以使用array_filter删除空元素:

$emptyRemoved = array_filter($linksArray);

If you have (int) 0in your array, you may use the following:

如果您(int) 0的数组中有,则可以使用以下内容:

$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

编辑:也许你的元素本身不是空的,而是包含一个或多个空格......你可以在使用之前使用以下内容array_filter

$trimmedArray = array_map('trim', $linksArray);

回答by Ron Cemer

The most popular answer on this topic is absolutely INCORRECT.

关于这个话题最流行的答案是绝对不正确的。

Consider the following PHP script:

考虑以下 PHP 脚本:

<?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.

为什么是这样?因为包含单个 '0' 字符的字符串也计算为布尔 false,所以即使它不是空字符串,它仍然会被过滤。那将是一个错误。

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.

将内置 strlen 函数作为过滤函数传递将起作用,因为它为非空字符串返回一个非零整数,为空字符串返回一个零整数。非零整数在转换为布尔值时总是评估为真,而零整数在转换为布尔值时总是评估为假。

So, the absolute, definitive, correct answer is:

所以,绝对的、确定的、正确的答案是:

$arr = array_filter($arr, 'strlen');

回答by tamasd

$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

“如果没有提供回调,所有等于 FALSE 的输入条目将被删除。” -- http://php.net/manual/en/function.array-filter.php

回答by matija kancijan

    $myarray = array_filter($myarray, 'strlen');  //removes null values but leaves "0"
    $myarray = array_filter($myarray);            //removes all null values

回答by helpse

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.

array_filter: "如果没有提供回调,所有等于 FALSE 的输入条目将被删除。" 这意味着值为 NULL、0、'0'、''、FALSE、array() 的元素也将被删除。

The other option is doing

另一种选择是做

array_diff($array, array(''))

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

这将删除值为 NULL、'' 和 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 ''
  • 0 或 '0' 将删除 0 和 '0'
  • NULL、FALSE 或 '' 将删除 NULL、FALSE 和 ''

回答by Mark Baker

foreach($linksArray as $key => $link) 
{ 
    if($link === '') 
    { 
        unset($linksArray[$key]); 
    } 
} 
print_r($linksArray); 

回答by marcovtwout

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

另一个用于从数组中删除空("" 空字符串)元素的衬垫。

$array = array_filter($array, function($a) {return $a !== "";});

Note: This code deliberately keeps null, 0and falseelements.

注意:这段代码故意保留null,0false元素。



Or maybe you want to trim your array elements first:

或者,您可能想先修剪数组元素:

$array = array_filter($array, function($a) {
    return trim($a) !== "";
});

Note: This code also removes nulland falseelements.

注意:此代码还删除了nullfalse元素。

回答by Nabi K.A.Z.

In short:

简而言之:

This is my suggested code:

这是我建议的代码:

$myarray =  array_values(array_filter(array_map('trim', $myarray), 'strlen'));

Explanation:

解释:

I thinks use array_filteris good, but not enough, because values be like spaceand \n,... keep in the array and this is usually bad.

我认为使用array_filter是好的,但还不够,因为值就像spaceand \n,... 保留在数组中,这通常是不好的。

So I suggest you use mixture ??array_filterand array_map.

所以我建议你使用混合物?array_filterarray_map

array_mapis for trimming, array_filteris for remove empty values, strlenis for keep 0value, and array_valuesis for re indexing if you needed.

array_map用于修剪,array_filter用于删除空值,strlen用于保留0值,array_values如果需要,用于重新索引。

Samples:

样品:

$myarray = array("\r", "\n", "\r\n", "", " ", "0", "a");

// "\r", "\n", "\r\n", " ", "a"
$new1 = array_filter($myarray);

// "a"
$new2 = array_filter(array_map('trim', $myarray));

// "0", "a"
$new3 = array_filter(array_map('trim', $myarray), 'strlen');

// "0", "a" (reindex)
$new4 = array_values(array_filter(array_map('trim', $myarray), 'strlen'));

var_dump($new1, $new2, $new3, $new4);

Results:

结果:

array(5) {
  [0]=>
" string(1) "
  [1]=>
  string(1) "
"
  [2]=>
  string(2) "
"
  [4]=>
  string(1) " "
  [6]=>
  string(1) "a"
}
array(1) {
  [6]=>
  string(1) "a"
}
array(2) {
  [5]=>
  string(1) "0"
  [6]=>
  string(1) "a"
}
array(2) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "a"
}

Online Test:

在线测试:

http://phpio.net/s/5yg0

http://phpio.net/s/5yg0

回答by mulquin

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

如果您使用的是数值数组并且需要在删除空元素后重新索引数组,请使用array_values函数:

array_values(array_filter($array));

Also see: PHP reindex array?

另请参阅:PHP 重新索引数组?