How to remove empty values from an array in PHP
Topic: PHP / MySQLPrev|Next
Answer: Use the PHP array_filter()
function
You can simply use the PHP 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.
However, if no callback function is specified, all empty entries of array will be removed, such as ""
(an empty string), 0
(0 as an integer), 0.0
(0 as a float), "0"
(0 as a string), NULL
, FALSE
and array()
(an empty array). Let's try out an example to understand how it actually works:
Example
Try this code »<?php
$array = array("apple", "", 0, 2, null, -5, "0", "orange", 10, false);
var_dump($array);
echo "<br>";
// Filtering the array
$result = array_filter($array);
var_dump($result);
?>
In the above example the values 0
and "0"
are also removed from the array. If you want to keep them, you can define a callback function as shown in the following example:
Example
Try this code »<?php
$array = array("apple", "", 0, 2, null, -5, "0", "orange", 10, false);
var_dump($array);
echo "<br>";
// Defining a callback function
function myFilter($var){
return ($var !== NULL && $var !== FALSE && $var !== "");
}
// Filtering the array
$result = array_filter($array, "myFilter");
var_dump($result);
?>
The callback function myFilter()
is called for each element of the array. If myFilter()
returns TRUE
, then that element will be appended to the result array, otherwise not.
Related FAQ
Here are some more FAQ related to this topic: