To remove empty values from an array in PHP, you can use the array_filter()
function. This function filters the elements of an array using a callback function, and returns an array with only the elements that pass the test implemented by the callback function.
For example, to remove empty values from an array, you can use the following code:
$array = array(0, 1, 2, '', 4, null, 6);
$array = array_filter($array);
After running this code, $array
will be equal to array(0, 1, 2, 4, 6)
.
If you want to remove not only empty values, but also values that are considered “falsy” (such as 0, false, null, etc.), you can pass a callback function to array_filter()
that returns true
for values that you want to keep, and false
for values that you want to remove.
For example:
$array = array(0, 1, 2, '', 4, null, 6);
$array = array_filter($array, function ($value) {
return $value !== '' && $value !== null;
});
This will remove all values that are equal to an empty string or null. The resulting array will be array(0, 1, 2, 4, 6)
.