Removing empty array elements in PHP


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.

Updated on: 02-Jul-2020

438 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements