15

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.

2

6 Answers 6

31

If you want a quick way to remove NULL, FALSE and Empty Strings (""), but leave values of 0 (zero), you can use the standard php function strlen as the callback function:

// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter( $array, 'strlen' );

Source: http://php.net/manual/en/function.array-filter.php#111091

Sign up to request clarification or add additional context in comments.

1 Comment

Note: this doesn't work on multidimentional arrays.
27

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

5 Comments

You may wish to use if ( empty( $value ) ) to be more comprehensive.
@GeorgeCummins: agree, that's an option. Internally, it does the same thing though - right?
empty() is more comprehensive because it also checks for 0, false, "0", 0.0, empty arrays, etc. It is also a little simpler to read and maintain.
@GeorgeCummins Fair enough, however this is not what he wants: he states that he only wants to filter out nulls and empty strings.
@chris said: "where the value is null, empty, or equal to '' ." Since he specifically said "empty" and didn't say "empty string" I assumed my interpretation was correct. Perhaps a little clarification from from the asker would be helpful.
6

array_filter is a built-in function that does exactly what you need. At the most you will need to provide your own callback that decides which values stay and which get removed. The keys will be preserved automatically, as the function description states.

For example:

// This callback retains values equal to integer 0 or the string "0".
// If you also wanted to remove those, you would not even need a callback
// because that is the default behavior.
function filter_callback($val) {
    $val = trim($val);
    return $val != '';
}

$filtered = array_filter($original, 'filter_callback');

Comments

1

If you want to remove null, undefined, '', 0, '0', but don't remove string ' '

$result = array_filter( $array, 'ucfirst' );

Comments

0

Filtering the array for PHP 7.4 and above use this

// Filtering the array
$result = array_filter($array, fn($var) => ($var !== NULL && $var !== FALSE && $var !== ""));

Comments

-3

use +1 with your key variable to skip null key in array

foreach($myarray as $key=>$value)
{
    echo $key+1; //skip null key
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.