'Remove Null values in PHP array
I have an array
array (size=7)
0 => string '2'
1 => string ''
2 => string ''
3 => string '0'
4 => string ''
5 => string ''
6 => string '2.5'
I used:-
array_filter()
to remove the null values and it returns
Array ( [0] => 2 [6] => 2 )
array_filter() removes null value and also '0' value.
Any builtin function is available in PHP to remove NULL values only.
Solution 1:[1]
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); });
Solution 2:[2]
You can remove empty value and then re-index the array elements by using array_values() and array_filter() function together as such:
$arr = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0);
print_r(array_values(array_filter($arr)));
Output:
Array
(
[0] => PHP
[1] => HTML
[2] => CSS
[3] => JavaScript
)
Solution 3:[3]
function myFilter($var){
return ($var !== NULL && $var !== FALSE && $var !== '');
}
$res = array_filter($yourArray, 'myFilter');
If you just need the numeric values you can use is_numeric as your callback
Demo
$res = array_filter($values, 'is_numeric');
Solution 4:[4]
As of PHP 7.4:
$withoutNulls = array_filter($withNulls, static fn($e) => $e !== null);
Solution 5:[5]
Remove null values from array
$array = array("apple", "", 2, null, -5, "orange", 10, false, "");
var_dump($array);
echo "<br>";
// Filtering the array
$result = array_filter($array);
var_dump($result);
?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Festus Ngor |
| Solution 3 | TarangP |
| Solution 4 | Matt Janssen |
| Solution 5 |
