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.
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.
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
You can use array_filter()
which will get rid of the null empty values from the array
print_r(array_filter($arr, 'strlen'));
You can just loop through it.
<?php
foreach ($array as $i=>$row) {
if ($row === null)
unset($array[$i]);
}
If you want to reindex the array to remove gaps between keys, you can just use a new array:
<?php
$array2 = array();
foreach ($array as $row) {
if ($row !== null)
$array2[] = $row;
}
$array = $array2;
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.
EDIT:
This is bad advice, because the trick leans on a strange corner case:
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"));
This is well readable.
<?php
$arr = array( 0 => 0, 1=>null, 2=>3, 3=>null);
foreach ($arr as $key=>$val) {
if ($val === null)
unset($arr[$key]);
}
$new_arr = array_values($arr);
print_r($new_arr);
?>
Out put:
Array
(
[0] => 0
[1] => 3
)
simply
$keys=array_keys($yourArray,NULL);
if(!empty($keys))
{
foreach($keys as $key)
{
unset($yourArray[$key]);
}
}
var_dump($yourarray);