Php array filter null values

How to remove null values from an array? [duplicate]

I have an array Array ( [0] => 0 [1] => [2] => 3 [3] => ) i want to remove null values from this and the result should be like this Array ( [0] => 0 [1] => 3) i don’t want to remove 0 value from array.

6 Answers 6

array_filter($arr, static function($var) ); 
function is_not_null ($var) < return !is_null($var); >$filtered = array_filter($arr, 'is_not_null'); 

@AlexP nope, you are wrong. as seen on 3v4l.org/Y9KCX your solution would remove everything that is empty() — not just NULL.

You can use array_filter() which will get rid of the null empty values from the array

print_r(array_filter($arr, 'strlen')); 

This does not work. $ php -r «var_dump(array_filter([0, null, false, ‘hi’, »], ‘strlen’));» array(2) < [0] =>int(0) [3] => string(2) «hi» >

From PHP8.1 this is no longer a good technique because it will generate Deprecations. Deprecated: strlen(): Passing null to parameter #1 ($string) of type string is deprecated

You can just loop through it.

If you want to reindex the array to remove gaps between keys, you can just use a new array:

You are in a world of trouble now, because it is not too easy to distinguish null from 0 from false from «» from 0.0. But don’t worry, it is solvable:

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

Which is horrible by itself, but seems to work.

This is bad advice, because the trick leans on a strange corner case:

  • strlen(0) will be strlen(«0») -> 1, thus true
  • strlen(NULL) will be strlen(«»)->0, thus false
  • strlen(«») will be strlen((«»)->0, thus false etc.

The way you should do it is something like this:

 $my_array = array(2, "a", null, 2.5, NULL, 0, "", 8); function is_notnull($v) < return !is_null($v); >print_r(array_filter($my_array, "is_notnull")); 

Источник

Remove empty values from PHP array but keep 0

array_filter() removes null value and also ‘0’ value. Any builtin function is available in PHP to remove NULL values only.

@Athi — that would also remove empty strings as well, which is not the same as NULL . You can use a closure as your callback to control what gets filtered.

«I used array_filter() to remove the null values» — your input array does not contain NULL values. It contain empty strings ( » ) and they are not the same as NULL . NULL means the absence of any value, an empty string is a string of length 0 . They are completely different concepts.

7 Answers 7

Assumption: I think you want to remove NULL as well as empty-strings/values » from your array. (What i understand from your desired output)

You have to use array_filter() with strlen()

Both 0 and » are considered falsey in php, and so would be removed by array filter without a specific callback. The suggestion above to use ‘strlen’ is also wrong as it also remove an empty string which is not the same as NULL . To remove only NULL values as you asked, you can use a closure as the callback for array_filter() like this:

array_filter($array, function($v) < return !is_null($v); >); 

Not your problem 🙂 Even I thought OP said Any builtin function is available in PHP to remove NULL values only. Until an edit

You can remove empty value and then re-index the array elements by using array_values() and array_filter() function together as such:

$arr = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0); print_r(array_values(array_filter($arr))); 
Array ( [0] => PHP [1] => HTML [2] => CSS [3] => JavaScript ) 
function myFilter($var) < return ($var !== NULL && $var !== FALSE && $var !== ''); >$res = array_filter($yourArray, 'myFilter'); 

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

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

In case your array could contain line feeds and you want to filter them out as well, you may want to trim values first:

$arrayItems = ["\r", "\n", "\r\n", "", " ", "0", "a"]; $newArray = array_values(array_filter(array_map('trim', $arrayItems), 'strlen')); // Output(newArray): ["0", "a"] //Another great snippet to remove empty items from array $newArray = array_filter($arrayItems , function ($item) < return !preg_match('/^\\s*$/', $item); // filter empty lines >); // Output(newArray): ["0", "a"] 

If you face any issue with implementing the code just comment here below.

Источник

Remove all `null` values from an array in PHP

A convenient method to remove all null values from an array in PHP is by using the array_filter() function. As the name suggests the method filters a given array, if you don’t supply your own filter function PHP filters out all values that evaluate as false in a condition; empty strings, 0 , false , null .

To explicitly only filter out the null values you should pass your own callback function to the array_filter() function that only returns false if a given value is equal to null .

Using an arrow function that would look like the following:

<?php $values = ['a', 'b', null, 'c']; $result = array_filter($values, fn ($value) => !is_null($value)); print_r($result); // Array // ( // [0] => a // [1] => b // [2] => c // ) 

As I mentioned above, if you don’t supply a callback function yourself PHP filters out all values that evaluate as false . So that includes other values besides null as well. But maybe that’s just what you need. In that case, see the example below:

<?php $values = ['a', '', null, false, []]; $result = array_filter($values); print_r($result); // Array // ( // [0] => a // ) 

Источник

php array_filter without key preservation

if i filter an array with array_filter to eliminate null values, keys are preserved and this generated «holes» in the array. Eg:

The filtered version of [0] => 'foo' [1] => null [2] => 'bar' is [0] => 'foo' [2] => 'bar' 

2 Answers 2

You could use array_values after filtering to get the values.

$array=['foo',NULL,'bar',0,false,null,'0','']; 

There are a few ways you could do it. Demo

It’s slightly off-topic to bring up array_filter ‘s greedy default behavior, but if you are googling to this page, this is probably important information relevant to your project/task:

var_export(array_values(array_filter($array))); // NOT GOOD. 

Now for the ways that will work:

Method #1: ( array_values() , array_filter() w/ !is_null() )

var_export(array_values(array_filter($array,function($v)))); // good 

Method #2: ( foreach() , auto-indexed array, !==null )

foreach($array as $v) < if($v!==null)<$result[]=$v;>> var_export($result); // good 

Method #3: ( array_walk() , auto-index array, !is_null() )

array_walk($array,function($v)use(&$filtered)>); var_export($filtered); // good 

All three methods provide the following «null-free» output:

array ( 0 => 'foo', 1 => 'bar', 2 => 0, 3 => false, 4 => '0', 5 => '', ) 

From PHP7.4, you can even perform a «repack» like this: (the splat operator requires numeric keys)

$array = ['foo', NULL, 'bar', 0, false, null, '0', '']; $array = [. array_filter($array)]; var_export($array); 

. but as it turns out, «repacking» with the splat operator is far less efficient than calling array_values() .

Источник

Читайте также:  Css ul стиль маркеров
Оцените статью