删除PHP数组中的Null值

Ath*_*thi 1 php

我有一个阵列

array (size=7)
0 => string '2' 
1 => string '' 
2 => string '' 
3 => string '0' 
4 => string '' 
5 => string '' 
6 => string '2.5' 
Run Code Online (Sandbox Code Playgroud)

我用了:-

array_filter()

删除空值并返回

Array ( [0] => 2 [6] => 2 )
Run Code Online (Sandbox Code Playgroud)

array_filter() 删除空值以及"0"值.

PHP中提供了任何内置函数,仅用于删除NULL值.

Ana*_*Die 11

注意: -我想你要删除数组中的NULL空字符串/值''.(我从你想要的输出中理解的是什么)

你必须使用 带有 strlen()的array_filter ()

array_filter($array,'strlen');
Run Code Online (Sandbox Code Playgroud)

输出: - https://eval.in/926585 AND https://eval.in/926595 AND https://eval.in/926602

Refrence: -

PHP:array_filter - 手册

PHP:strlen - 手册

  • 除了“null”和“''”之外,这还将过滤掉“false” (5认同)

bil*_*oah 10

Both 0 and '' are considered falsey in php, and so would be removed by array filter without a specific callback. The suggestion above to use 'strlen' is also wrong as it also remove an empty string which is not the same as NULL. To remove only NULL values as you asked, you can use a closure as the callback for array_filter() like this:

array_filter($array, function($v) { return !is_null($v); });
Run Code Online (Sandbox Code Playgroud)

  • @Athi - 那是因为你的问题中的数组不包含“NULL”值。 (3认同)
  • 不是你的问题:)即使我认为OP说*任何内置函数都可以在PHP中仅删除NULL值。* **直到编辑** (2认同)