Q:

How to remove empty values from an array in PHP

0

How to remove empty values from an array in PHP

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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), NULLFALSE and array() (an empty array). Let's try out an example to understand how it actually works:

<?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:

<?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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP  and MySQL Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to populate dropdown list with array values in... >>
<< How to calculate the sum of values in an array in ...