Tuesday, December 14, 2010

PHP: How to remove empty values from an array

This function removes empty values from an array. This is useful if you’re working with dynamical arrays (for instance data harvested from a web site).



<?php
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/web-programming/php/remove-empty-values-from-an-array.html
*/
function remove_array_empty_values($array, $remove_null_number = true)
{
$new_array = array();

$null_exceptions = array();

foreach ($array as $key => $value)
{
$value = trim($value);

        if($remove_null_number)
{
       $null_exceptions[] = '0';
}

        if(!in_array($value, $null_exceptions) && $value != "")
{
            $new_array[] = $value;
        }
    }
    return $new_array;
}
?>

Example of usage:

$array = array("white", "yellow", 0, "green", " ", "navy");

$remove_null_number = true;
$new_array = remove_array_empty_values($array, $remove_null_number);

echo '<pre>'; print_r($new_array); echo '</pre>';

Array
(
    [0] => white
    [1] => yellow
    [2] => green
    [3] => navy
)

The new array will look like this:

No comments:

Post a Comment