52

I want to remove NULL, FALSE and '' values .

I used array_filter but it removes the 0' s also.

Is there any function to do what I want?

array(NULL,FALSE,'',0,1) -> array(0,1)

9 Answers 9

69

array_filter should work fine if you use the identical comparison operator.

here's an example

$values = [NULL, FALSE, '', 0, 1];

function myFilter($var){
  return ($var !== NULL && $var !== FALSE && $var !== '');
}

$res = array_filter($values, 'myFilter');

Or if you don't want to define a filtering function, you can also use an anonymous function (closure):

$res = array_filter($values, function($value) {
    return ($value !== null && $value !== false && $value !== ''); 
});

If you just need the numeric values you can use is_numeric as your callback: example

$res = array_filter($values, 'is_numeric');
Sign up to request clarification or add additional context in comments.

2 Comments

The second example is a bit dangerous, since you don't know what sort of data OP is filtering. That filter will remove much more than just NULL, FALSE, and "".
true, added a note to the answer.
66

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

If you want to remove NULL, FALSE and Empty Strings, but leave values of 0, you can use strlen as the callback function:

array_filter($array, 'strlen');

3 Comments

That does actually work because strlen() casts its parameter to string- so 0 and 1 become "0" and "1", while null and false become "".
Genius! Just note that objects and arrays will be removed as well, and strlen will throw warnings about them.
As of PHP 8.1, strlen will now emit a deprecated error "strlen(): Passing null to parameter #1 ($string) of type string is deprecated"
6

array_filter doesn't work because, by default, it removes anything that is equivalent to FALSE, and PHP considers 0 to be equivalent to false. The PHP manual has this to say on the subject:

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

You can pass a second parameter to array_filter with a callback to a function you write yourself, which tells array_filter whether or not to remove the item.

Assuming you want to remove all FALSE-equivalent values except zeroes, this is an easy function to write:

function RemoveFalseButNotZero($value) {
  return ($value || is_numeric($value));
}

Then you just overwrite the original array with the filtered array:

$array = array_filter($array, "RemoveFalseButNotZero");

2 Comments

Or if you like lambdas: $array= array_filter($array, function($val) { return ($val || is_numeric($val));});
@bmewburn You need to remove the negation. The callback returns TRUE if you want to keep the value. I misremembered when I wrote the answer originally.
2

Use a custom callback function with array_filter. See this example, lifted from PHP manual, on how to use call back functions. The callback function in the example is filtering based on odd/even; you can write a little function to filter based on your requirements.

<?php
function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}

function even($var)
{
    // returns whether the input integer is even
    return(!($var & 1));
}

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));
echo "Even:\n";
print_r(array_filter($array2, "even"));
?> 

2 Comments

I'm not sure why this was down-voted :( Okay, perhaps the callback functions could be written differently, and perhaps it could have used the data in the post, but it likely shows a usage not considered by the OP. (I am out of votes myself ..)
It does not show exact call back because I was not in a mood to spoon feed. The answer itself says that 'The callback function in the example is filtering based on odd/even; you can write a little function to filter based on your requirements.' AND that I lifted it off from the PHP manual.
1

One-liners are always nice.

$clean_array = array_diff(array_map('trim', $my_array), array('', NULL, FALSE));

Explanation:

  • 1st parameter of array_diff: The trimmed version of $my_array. Using array_map, surrounding whitespace is trimmed from every element via the trim function. It is good to use the trimmed version in case an element contains a string that is nothing but whitespace (i.e. tabs, spaces), which I assume would also want to be removed. You could just as easily use $my_array for the 1st parameter if you don't want to trim the elements.
  • 2nd parameter of array_diff: An array of items that you would like to remove from $my_array.
  • Output: An array of elements that are contained in the 1st array that are not also contained in the 2nd array. In this case, because '', NULL, and FALSE are within the 2nd array, they can never be returned by array_diff.

EDIT:

It turns out you don't need to have NULL and FALSE in the 2nd array. Instead you can just have '', and it will work the same way:

$clean_array = array_diff(array_map('trim', $my_array), array(''));

Comments

0
function my_filter($var)
{
    // returns values that are neither false nor null (but can be 0)
    return ($var !== false && $var !== null && $var !== '');
}

$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => '',
             5 => 0
          );

print_r(array_filter($entry, 'my_filter'));

Outputs:

Array
(
    [0] => foo
    [2] => -1
    [5] => 0
)

Comments

0

check whether it is less than 1 and greater than -1 if then dont remove it...

$arrayValue = (NULL,FALSE,'',0,1);
$newArray = array();
foreach($arrayValue as $value) {
    if(is_int($value) || ($value>-1 && $value <1)) {
        $newArray[] = $value;
    }
}

print_r($newArray);

2 Comments

What if it was array(NULL,FALSE,'hello world')?
Will he have characters/string in it?
0

Alternatively you can use array_filter with the 'strlen' parameter:

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

https://www.php.net/manual/en/function.array-filter.php#111091

2 Comments

This throws errors if your array contains other arrays.
and as of PHP 8.1, strlen will now emit a deprecated error "strlen(): Passing null to parameter #1 ($string) of type string is deprecated"
-2
function ExtArray($linksArray){
    foreach ($linksArray as $key => $link)
    {
        if ($linksArray[$key] == '' || $linksArray[$key] == NULL || $linksArray[$key] == FALSE || $linksArray[$key] == '')
        {
            unset($linksArray[$key]);
        }else {
            return $linksArray[$key];
        }
    }
}

This function may help you

1 Comment

This is ugly and it will have the same problem as OP had. You have to use the identical comparison operator. Good solution have 3 lines at most and you don't even have to define a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.