How to remove empty values from an array in PHP?

You can use the array_filter function to remove empty values from an array. This function will pass each element of the array to a callback function for evaluation, filtering out any elements where the callback function returns false.

Here is an example code:

<?php
$array = array("apple", "", "banana", null, "orange");

// 去掉空值
$array = array_filter($array);

// 打印结果
print_r($array);
?>

The output is:

Array
(
    [0] => apple
    [2] => banana
    [4] => orange
)

In the example above, only “apple”, “banana”, and “orange” were kept, while empty strings and null values were filtered out.

bannerAds