Remove empty values from array PHP
In this post, you will learn how to remove empty values from an array using the PHP programming language.
In the website development, we may face a situation where an array contains one or more empty values that we need to remove. It is easy process to remove empty values from an array. PHP provides array_filter() function to remove or filter empty values from an array. This function typically filters the values of an array using a callback function. If no callback function is specified, all empty entries of an array will be removed. This will also remove blank, null, false, 0 (zero) values.
Syntax
array_filter($array, $callbackFunction, $callbackParameter)
Here the $array is the only required parameter. The parameter $callbackFunction is the callback function specified for the operation on the array. The parameter $callbackParameter tells about the parameters passed to the callback function.
$array = array("Banana", 0, NULL, "Apple", 0, "Papaya", "Orange", NULL, 0);
var_dump($array);
// filtering the array
$result = array_filter($array);
var_dump($result);
Output of the above code:
array (size=9)
0 => string 'Banana' (length=6)
1 => int 0
2 => null
3 => string 'Apple' (length=5)
4 => int 0
5 => string 'Papaya' (length=6)
6 => string 'Orange' (length=6)
7 => null
8 => int 0
array (size=4)
0 => string 'Banana' (length=6)
3 => string 'Apple' (length=5)
5 => string 'Papaya' (length=6)
6 => string 'Orange' (length=6)
Use empty() with unset() function
We can also use the empty() along with the unset() function to remove the empty values from an array. The empty() function is used to check if an element is empty or not and the unset() function remove the empty array elements in PHP.
<?php
// Array declaration
$array = array("Apple", null, 0, null, "Orange", false, "Pineapple");
// Find empty elements and
// unset the empty elements
foreach($array as $key => $value)
if(empty($value))
unset($array[$key]);
// Print the array elements
var_dump($array);
?>
Output of the above code:
array (size=3)
0 => string 'Apple' (length=5)
4 => string 'Orange' (length=6)
6 => string 'Pineapple' (length=9)
Related Articles
PHP reverse a string without predefined functionPHP random quote generator
PHP convert string into an array
PHP remove HTML and PHP tags from string
Import Excel File into MySQL using PHP
PHP array length
Import Excel File into MySQL Database using PHP
PHP String Contains
PHP remove last character from string
PHP random quote generator
PHP calculate percentage of total
PHP sanitize input for MySQL
Display PDF using an AJAX call
How to fetch data from database in php and display in pdf
How to read CSV file in PHP and store in MySQL
How to create a doc file using PHP
PHP SplFileObject Examples
How to Upload a File in PHP
Sending HTML form data to an email address