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("geeks", 11, '', null, 12, "for", 1997, false, "geeks"); // Function to remove empty elements // from array $filtered_array = array_filter($array); // Display the filtered array var_dump($filtered_array); ?> |
array(6) {
[0]=>
string(5) "geeks"
[1]=>
int(11)
[4]=>
int(12)
[5]=>
string(3) "for"
[6]=>
int(1997)
[8]=>
string(5) "geeks"
}
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("geeks", 11, '', null, 12, "for", 1997, false, "geeks"); // 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>"); ?> |
geeks
11
12
for
1997
geeks
Recommended Posts:
- JavaScript | Remove empty elements from an array
- PHP | Remove duplicate elements from Array
- How to check whether an array is empty using PHP?
- How to empty an array in JavaScript?
- Best way to initialize empty array in PHP
- Check if an array is empty or not in JavaScript
- jQuery | Remove Elements
- How to remove the space between inline-block elements?
- Remove all the child elements of a DOM node in JavaScript
- JavaScript | Remove the last item from an array
- How to remove an element from an array in JavaScript?
- How to remove an array element in a foreach loop?
- How to get all unique values (remove duplicates) in a JavaScript array?
- D3.js | d3.map.empty() Function
- D3.js | d3.set.empty() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



