Removing empty array elements in PHP

PHPServer Side ProgrammingProgramming

To remove empty array elements in PHP, the code is as follows −

Example

 Live Demo

<?php
   $my_array = array("This", 91, '', null, 102, "is", false, "a", "sample", null);
   foreach($my_array as $key => $val)
   if(empty($val))
      unset($my_array[$key]);
   echo "After removing null values from the array, the array has the below elements -";
   foreach($my_array as $key => $val)
   echo ($my_array[$key] ."<br>");
?>

Output

After removing null values from the array, the array has the below elements -This
91
102
is
a
sample

An array is defined, that contains strings, numbers and ‘null’ values. The ‘foreach’ loop is used to iterate over the elements and if a value is empty, i.e. it contains null, then it is deleted from the array. The relevant array is displayed again that wouldn’t contain null values.

raja
Published on 02-Jul-2020 06:22:32
Advertisements