从 PHP 数组中删除 NULL、FALSE 和 '' - 但不是 0 -

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14134006/
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 06:43:47  来源:igfitidea点击:

Remove NULL, FALSE, and '' - but not 0 - from a PHP array

phparraysarray-filter

提问by Kanishka Panamaldeniya

I want to remove NULL, FALSEand ''values .

我想删除NULL,FALSE''values 。

I used array_filterbut it removes the 0' s also.

我用过,array_filter但它也删除了0's。

Is there any function to do what I want?

有什么功能可以做我想做的事吗?

array(NULL,FALSE,'',0,1) -> array(0,1)

回答by Max Girkens

array_filtershould work fine if you use the identicalcomparison operator.

array_filter如果您使用identical比较运算符,应该可以正常工作。

here's an example

这是一个例子

$values = [NULL, FALSE, '', 0, 1];

function myFilter($var){
  return ($var !== NULL && $var !== FALSE && $var !== '');
}

$res = array_filter($values, 'myFilter');

Or if you don't want to define a filtering function, you can also use an anonymous function(closure):

或者如果不想定义过滤函数,也可以使用匿名函数(闭包):

$res = array_filter($values, function($value) {
    return ($value !== null && $value !== false && $value !== ''); 
});

If you just need the numeric values you can use is_numericas your callback: example

如果您只需要数值,您可以使用is_numeric作为您的回调:示例

$res = array_filter($values, 'is_numeric');

回答by Vladyslav Savchenko

From http://php.net/manual/en/function.array-filter.php#111091:

来自http://php.net/manual/en/function.array-filter.php#111091

If you want to remove NULL, FALSE and Empty Strings, but leave values of 0, you can use strlen as the callback function:

如果要删除 NULL、FALSE 和 Empty 字符串,但保留值为 0,则可以使用 strlen 作为回调函数:

array_filter($array, 'strlen');

回答by AgentConundrum

array_filterdoesn't work because, by default, it removes anything that is equivalent to FALSE, and PHP considers 0to be equivalent to false. The PHP manualhas this to say on the subject:

array_filter不起作用,因为默认情况下,它会删除任何等效于 的内容FALSE,而 PHP 认为0等效于 false。在PHP手册中有这样一段关于这个问题说:

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

转换为布尔值时,以下值被视为 FALSE:

  • 布尔值 FALSE 本身
  • 整数 0(零)
  • 浮点数 0.0(零)
  • 空字符串和字符串“0”
  • 一个元素为零的数组
  • 具有零成员变量的对象(仅限 PHP 4)
  • 特殊类型 NULL(包括未设置的变量)
  • 从空标签创建的 SimpleXML 对象

每隔一个值都被认为是 TRUE(包括任何资源)。

You can pass a second parameter to array_filterwith a callback to a function you write yourself, which tells array_filterwhether or not to remove the item.

您可以通过array_filter回调将第二个参数传递给您自己编写的函数,该函数告诉您array_filter是否删除该项目。

Assuming you want to remove all FALSE-equivalent values exceptzeroes, this is an easy function to write:

假设您要删除以外的所有 FALSE 等效值,这是一个易于编写的函数:

function RemoveFalseButNotZero($value) {
  return ($value || is_numeric($value));
}

Then you just overwrite the original array with the filtered array:

然后你只需用过滤后的数组覆盖原始数组:

$array = array_filter($array, "RemoveFalseButNotZero");

回答by Amit

Use a custom callback function with array_filter. See this example, lifted from PHP manual, on how to use call back functions. The callback function in the example is filtering based on odd/even; you can write a little function to filter based on your requirements.

将自定义回调函数与 array_filter 一起使用。请参阅从 PHP 手册中提取的有关如何使用回调函数的示例。示例中的回调函数是基于奇数/偶数的过滤;您可以编写一个小函数来根据您的要求进行过滤。

<?php
function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}

function even($var)
{
    // returns whether the input integer is even
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?> 

回答by seane

One-liners are always nice.

单线总是很好。

$clean_array = array_diff(array_map('trim', $my_array), array('', NULL, FALSE));

Explanation:

解释:

  • 1st parameter of array_diff:The trimmed version of $my_array. Using array_map, surrounding whitespace is trimmed from every element via the trimfunction. It is good to use the trimmed version in case an element contains a string that is nothing but whitespace (i.e. tabs, spaces), which I assume would also want to be removed. You could just as easily use $my_array for the 1st parameter if you don't want to trim the elements.
  • 2nd parameter of array_diff:An array of items that you would like to remove from $my_array.
  • Output:An array of elements that are contained in the 1st array that are not also contained in the 2nd array. In this case, because '', NULL, and FALSEare within the 2nd array, they can never be returned by array_diff.
  • 的第一个参数array_diff的修剪版本$my_array。使用array_map,通过该trim函数从每个元素中修剪周围的空白。如果一个元素包含一个只有空格(即制表符、空格)的字符串,我认为这些字符串也需要删除,那么最好使用修剪后的版本。如果您不想修剪元素,您可以轻松地将 $my_array 用于第一个参数。
  • 的第二个参数array_diff要从中删除的项目数组$my_array
  • 输出:包含在第一个数组中但不包含在第二个数组中的元素数组。在这种情况下,因为''NULL、 和FALSE在第二个数组中,它们永远不会被 返回array_diff

EDIT:

编辑:

It turns out you don't need to have NULLand FALSEin the 2nd array. Instead you can just have '', and it will work the same way:

事实证明,您不需要在第二个数组中拥有NULLFALSE。相反,您可以只拥有'',它的工作方式相同:

$clean_array = array_diff(array_map('trim', $my_array), array(''));

回答by Marcio Bera

Alternatively you can use array_filterwith the 'strlen'parameter:

或者,您可以array_filter'strlen'参数一起使用:

// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter($array, 'strlen');

https://www.php.net/manual/en/function.array-filter.php#111091

https://www.php.net/manual/en/function.array-filter.php#111091

回答by Vinoth Babu

check whether it is less than 1 and greater than -1 if then dont remove it...

检查它是否小于 1 和大于 -1 如果然后不删除它...

$arrayValue = (NULL,FALSE,'',0,1);
$newArray = array();
foreach($arrayValue as $value) {
    if(is_int($value) || ($value>-1 && $value <1)) {
        $newArray[] = $value;
    }
}

print_r($newArray);

回答by Wojciech Zylinski

function my_filter($var)
{
    // returns values that are neither false nor null (but can be 0)
    return ($var !== false && $var !== null && $var !== '');
}

$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => '',
             5 => 0
          );

print_r(array_filter($entry, 'my_filter'));

Outputs:

输出:

Array
(
    [0] => foo
    [2] => -1
    [5] => 0
)

回答by THE ONLY ONE

function ExtArray($linksArray){
    foreach ($linksArray as $key => $link)
    {
        if ($linksArray[$key] == '' || $linksArray[$key] == NULL || $linksArray[$key] == FALSE || $linksArray[$key] == '')
        {
            unset($linksArray[$key]);
        }else {
            return $linksArray[$key];
        }
    }
}

This function may help you

这个功能可以帮到你