I want to remove empty rows from array in php
, I used array_filter
that gives perfect result.
Here is my code which I have tried
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("",'','')
);
$cars= array_filter(array_map('array_filter', $cars));
echo "<pre>"; print_r($cars);
the output is following for above array is :-
Array
(
[0] => Array
(
[0] => Volvo
[1] => 22
[2] => 18
)
[1] => Array
(
[0] => BMW
[1] => 15
[2] => 13
)
[2] => Array
(
[0] => Saab
[1] => 5
[2] => 2
)
)
the output is perfect as it removed the empty rows, but when I create new array like below
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("",54,'')
);
in last array it remove the first and last column and keep it remain the 1 position column in the array. like below:-
Array
(
[0] => Array
(
[0] => Volvo
[1] => 22
[2] => 18
)
[1] => Array
(
[0] => BMW
[1] => 15
[2] => 13
)
[2] => Array
(
[0] => Saab
[1] => 5
[2] => 2
)
[3] => Array
(
[1] => 54
)
)
I only want to remove empty row not the column so array return should be like below
Array
(
[0] => Array
(
[0] => Volvo
[1] => 22
[2] => 18
)
[1] => Array
(
[0] => BMW
[1] => 15
[2] => 13
)
[2] => Array
(
[0] => Saab
[1] => 5
[2] => 2
)
[3] => Array
(
[0] => ''
[1] => 54
[2] => ''
)
)
Simple solution:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("",'','')
);
// Here we `implode` all values of current subarray
// and if this imploded string is empty - skip subarray
$cars = array_filter($cars, function($v) { return implode('', $v) !== ''; });
echo '<pre>', print_r($cars), '</pre>';