How to remove null values from array in PHP

Hi all,
Today we study how to remove null values from an array.Its very important, to display all array values after removing NULL values in php code. If you have an array with NULL values but if you want to remove the NULL values from that array without loop. In PHP array_filter function helps to remove all null values from array.

Example1

$example1 = array(100, "Priya", null, "Varghese", NULL, "", 77);
 
$result1 = array_filter($example1, function($value) {
			  return !is_null($value);
			});
print_r($result1);

The Output as follows:

Array
(
[0] => 100
[1] => Priya
[3] => Varghese
[5] =>
[6] => 77
)

Example 2:

$myArray = array( 0, 'Apple', '', 'Orange' );
print_r( array_filter( $myArray ) );

The output as follows:

Array
(
[1] => ‘Apple’
[3] => ‘Orange’
)
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.

Leave a Reply

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