Share Article To

PHP – remove empty values from array

An easy and quick way to remove the empty value keys from an array is given below.

Lets assume below is our array
$array = array(‘data1′,”,’data3′,’data4’);

Now if we print this array using below code
echo “<pre>”;
print_r($array);
echo “<pre>”;

Result:
Array
(
    [0] => data1
    [1] =>
    [2] => data3
    [3] => data4
)
Now we pass the array that is $array to the below array_filter() function like below:

Case1: To Remove NULL values only:
$array = array_filter($array, ‘strlen’);

Case2: To Remove False Values:
$array = array_filter($array);

and then print the array again then we will get array like below
Array
(
    [0] => data1
    [2] => data3
    [3] => data4
)

So from above you can see the empty value removed from the array.

You can test the above examples with following arrays to get more clear idea

$array = array(‘data1′,”,’data3′,’data4’);
$array = array(‘data1′,0,’data3′,’data4’);
$array = array(‘data1′,true,’data3′,’data4’);
$array = array(‘data1′,false,’data3′,’data4’);

Leave a Reply

Your email address will not be published. Required fields are marked *