During our development process, what method would you think of when judging that the array is empty? The first thing that comes to mind should be the empty function, but it is wrong to directly use the empty function to determine if it is empty, because when the value is multi-dimensional, the empty result has a value.
In fact, we can use the array_filter function to easily remove multi-dimensional null values without changing the subscript of the array. Here is an example usage:
Thearray_filter() function uses a callback function to filter the elements in the array. If the custom filter function returns true, the current value of the operated array will be included in the returned result array, and the result will be formed into a new array. If the original array is an associative array, the key names remain unchanged.
The code is as follows | Copy code | ||||
$array = array( 0 => 'Frost Sky Tribe', 1 => false, 2 => 1, 3 => null, 4 => '', 5 => 'http://www.hzhuti.com', 6 => '0' ); print_r(array_filter($array)); ?> The output result of the above code is: Array ( [0] => Frost Sky Tribe [2] => 1 [5] => http://www.hzhuti.com )
|
代码如下 | 复制代码 |
function delEmpty($v) { if ($v==="" || $v==="php") //当数组中存在空值和php值时,换回false,也就是去掉该数组中的空值和php值 { return false; } return true; } $a=array(0=>"pig",1=>"Cat",2=>"",3=>"php"); print_r(array_filter($a,"delEmpty")); |
TechArticle