How to remove null values with PHP?

PHPServer Side ProgrammingProgramming

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 )
raja
Published on 12-Oct-2020 12:17:20
Advertisements