Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP remove empty, null Array key/values while keeping key/values otherwise not empty/null

Tags:

arrays

php

I have an array thats got about 12 potential key/value pairs. That are based off a _POST/_GET

The keys are not numeric as in 0-n, and I need to retain the keys with there values where applicable. My issue is I know that on occasion a key will be passed where the value is null, empty, or equal to ''. In the event thats the case I want to trim out those keys before processing my array. As running down the line without something there is going to break my script.

Now a while back I either made or found this function (I don't remember which its been in my arsenal for a while, either way though).

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;
    }

What I would love to do is very similar to this, however this works well with arrays that can have n-n key values and I am not dependent upon the key as well as the value to determine whats what where and when. As the above will just remove everything basically then just rebuilt the array. Where I am stuck is trying to figure out how to mimic the above function but where I retain the keys I need.

like image 904
chris Avatar asked Mar 05 '12 14:03

chris


People also ask

How do you remove Blank values from an array?

In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function.

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

Is an empty array null in PHP?

An empty array, an array value of null, and an array for which all elements are the null value are different from each other. An uninitialized array is a null array.

How do you clear an array in PHP?

Basic example of empty array:$emptyArray = ( array ) null; var_dump( $emptyArray );


1 Answers

If I understand correctly what you're after, you can use array_filter() or you can do something like this:

foreach($myarray as $key=>$value)
{
    if(is_null($value) || $value == '')
        unset($myarray[$key]);
}
like image 144
Aleks G Avatar answered Oct 16 '22 06:10

Aleks G