Remove null values from PHP array

When we need to filter any array then we use array_filter.

array_filter — Filters elements of an array using a callback function.  I have an array with some null values so i want to remove null values from array.

Array ( [0] => 1, [1] => 10,  [2] => 11, [3] => , [4] => 15, [5] => , [6] => 7 )

In above array, [3] and [5] does not contain any value so i want to remove null values from array. I was looking for 2-3 line of code that can filter null values from array. Below is the php code with array example to filter null values –

<?php
$arr = array(1,null,10,11,null,15,7,null);
$filtered = array_filter($arr, function($var){return !is_null($var);} );
print_r($filtered);
?>

Above code will work on all updated PHP versions from PHP 5.3 to 5.6.

remove-null-array-php

For older versions of php code will be 2 liner –

 

<?php

$arr = array(1,null,10,11,null,15,7,null);

function is_not_null ($var) { return !is_null($var); }
$filtered = array_filter($arr, 'is_not_null');

print_r($filtered);
?>

Leave a Reply