How to remove null values with PHP?


To remove null value in PHP, use array_filter(). It filters the array values. Let’s say the following is our array −

$studentDetails = array("firstName" => "John",  "lastName"=> null);
echo "The original value is=";print_r($studentDetails);

Let’s filter with array_filter() −

$result = array_filter($studentDetails);

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
   $studentDetails = array("firstName" => "John",  "lastName"=> null);
   echo "The original value is=";
   print_r($studentDetails);
   $result = array_filter($studentDetails);
   echo "</br>";  
   echo "After removing null part,the result is=";
   print_r($result);
?>
</body>
</html>

Output

The original value is=Array ( [firstName] => John [lastName] => )
After removing null part,the result is=Array ( [firstName] => John )

Updated on: 12-Oct-2020

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements