Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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.

like image 393
user3056158 Avatar asked Dec 19 '13 08:12

user3056158


People also ask

How do you remove duplicate values from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

How do you remove nulls from an array?

To remove all null values from an array:Declare a results variable and set it to an empty array. Use the forEach() method to iterate over the array. Check if each element is not equal to null . If the condition is satisfied, push the element into the results array.


2 Answers

this will do the trick:

array_filter($arr, static function($var){return $var !== null;} );

Code Example: https://3v4l.org/jtQa2


for older versions (php<5.3):

function is_not_null ($var) { return !is_null($var); }
$filtered = array_filter($arr, 'is_not_null');

Code Example: http://3v4l.org/CKrYO

like image 161
floww Avatar answered Oct 12 '22 19:10

floww


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

print_r(array_filter($arr, 'strlen'));
like image 29
Mr. Alien Avatar answered Oct 12 '22 17:10

Mr. Alien