Monday, June 15, 2026
HomeLanguagesProgram to remove empty array elements in PHP

Program to remove empty array elements in PHP

Given an array containing elements. The task is to remove empty elements from the array such as an empty string or a NULL element.

Method 1: Using array_filter() Function. It is achieved by using array_filter() function. It also removes false values when declared using a callback function, however, if no callback function is specified, all the values of the array which are equal to FALSE will be removed, such as an empty string or a NULL value.

Example:




<?php
  
// Declare array and stored array value
$array = array("neveropen", 11, '', null, 12, 
            "for", 1997, false, "neveropen");
              
// Function to remove empty elements
// from array
$filtered_array = array_filter($array);
  
// Display the filtered array
var_dump($filtered_array);
?>


Output:

array(6) {
  [0]=>
  string(5) "neveropen"
  [1]=>
  int(11)
  [4]=>
  int(12)
  [5]=>
  string(3) "for"
  [6]=>
  int(1997)
  [8]=>
  string(5) "neveropen"
}

Method 2: Using unset() Function. Another approach is to remove empty elements from array is using empty() function along with the unset() function. The empty() function is used to check if an element is empty or not.

Example:




<?php
  
// Declare array and stored array value
$array = array("neveropen", 11, '', null, 12, 
           "for", 1997, false, "neveropen");
             
// Loop to find empty elements and 
// unset the empty elements
foreach($array as $key => $value)         
    if(empty($value))
        unset($array[$key]);
          
// Display the array elements        
foreach($array as $key => $value)         
    echo ($array[$key] . "<br>");
?>


Output:

neveropen
11
12
for
1997
neveropen
RELATED ARTICLES

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS