Borja Borja - 4 months ago 9
PHP Question

Removing the entire subarray that contains a null value from multidmensional array in PHP

Having this kind of simply array:

array(3) {
[0]=
array(5) {
[0]=
string(61) "ramdom test"
[1]=
string(7) "19"
[2]=
string(7) "-99"
[3]=
string(6) "ramdom test"
[4]=
string(31) "ramdom test"
}
[1]=
array(5) {
[0]=
string(61) "ramdom test 2"
[1]=
string(7) "87"
[2]=
string(7) "-42"
[3]=
string(6) "NULL" // <--------------------------- THIS HAS A NULL VALUE
[4]=
string(31) "ramdom test 2"
}
[2]=
array(5) {
[0]=
string(61) "ramdom test 3"
[1]=
string(7) "54"
[2]=
string(7) "-67"
[3]=
string(6) "ramdom test 3"
[4]=
string(31) "ramdom test 3"
}
}


I want to remove the entire subarray that contains a
NULL
value, in this case, the key
[3]
of the
[1]
array has null, so how I want to remove the entire
[1]
array so I can get following desired output?

array(2) {
[0]=
array(5) {
[0]=
string(61) "ramdom test"
[1]=
string(7) "19"
[2]=
string(7) "-99"
[3]=
string(6) "ramdom test"
[4]=
string(31) "ramdom test"
}
[1]=
array(5) {
[0]=
string(61) "ramdom test 3"
[1]=
string(7) "54"
[2]=
string(7) "-67"
[3]=
string(6) "ramdom test 3"
[4]=
string(31) "ramdom test 3"
}
}


I'm using:

$myArray = array_map('array_filter', $myArray);


But this removes me only the null item, not the entire subarray.

Thanks in advance.

Inf Inf
Answer

Use array_filter function:

$result = array_filter($array, function($v){
  return !in_array(null, $v, true);
});

# fix keys
$result = array_values($result);

More details: http://php.net/manual/en/function.array-filter.php

Comments