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

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

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


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');

Tags:

Php

Arrays