remove null elements in php

To remove null elements from a PHP array, you can use a combination of array_filter() and unset() functions. The array_filter() function will create a new array with all the elements of the original array, for which the callback function returns true. The unset() function will remove the element at the specified index from the array.

Here's an example code snippet:

main.php
$array = array(1, 2, null, 3, null, 4);

$array = array_filter($array, function($value) {
    return !is_null($value);
});

foreach ($array as $value) {
    echo $value . "\n";
}
179 chars
10 lines

In this example, we first define an array with some null elements. We then use array_filter() to create a new array that only contains non-null elements. The callback function checks if the value is not null, and returns true if it is not. Finally, we iterate over the new array to output its elements.

Output:

main.php
1
2
3
4
8 chars
5 lines

related categories

gistlibby LogSnag