In PHP, sometimes we need to remove null values in an array so that we can better process the data. This article will explore different ways to remove null values from an array.
Method 1: Use the array_filter function
The array_filter() function is PHP’s built-in function for filtering array elements. When a callback function is passed, the function returns a function that only contains the return value of the callback function. A new array that is not FALSE (that is, not null, 0, " ", "0", false, array()). We can use this function to remove null values in the array. The sample code is as follows:
$arr = array('foo', 0, '', null, false, 'bar', ' ', '0', array()); $arr = array_filter($arr); //过滤 print_r($arr); //只剩下 'foo'、'bar'
The result is as follows:
Array ( [0] => foo [5] => bar )
Method 2: Use foreach loop to traverse the array
We also You can use a foreach loop to traverse the array and manually remove the null values. The sample code is as follows:
$arr = array('foo', 0, '', null, false, 'bar', ' ', '0', array()); foreach ($arr as $key => $value) { if (empty($value)) { unset($arr[$key]); //去除数组中的空值 } } print_r($arr); //只剩下 'foo'、'bar'
The result is also:
Array ( [0] => foo [5] => bar )
Method 3: Use the array_diff function
We also You can use the array_diff() function, which is used to return an array that contains all values in the first parameter array but not in the remaining parameter arrays. In other words, we can put the null value into the second parameter. The sample code is as follows:
$arr = array('foo', 0, '', null, false, 'bar', ' ', '0', array()); $arr = array_diff($arr, array('')); //去除数组中的空值 print_r($arr); //只剩下 'foo'、'bar'
The result is also:
Array ( [0] => foo [5] => bar )
In summary, we have many methods Null values can be removed from PHP arrays, using the array_filter() function is the most convenient. However, if you need to manually process each element in the array, it may be better to use a foreach loop.
The above is the detailed content of How to remove null values from an array in php. For more information, please follow other related articles on the PHP Chinese website!