Reputation: 5685
How do you remove the lines that have empty elements from a multidimensional-array in PHP?
For instance, from:
1: a, b, c, d
2: d, _, b, a
3: a, b, _, _
4: d, c, b, a
5: _, b, c, d
6: d, c, b, a
to
1: a, b, c, d
4: d, c, b, a
6: d, c, b, a
Thanks!
Upvotes: 2
Views: 1978
Reputation: 1535
Try this:
Note: $arr is your array.
foreach ( $arr as $key => $line ) {
foreach ( $line as $item ) {
if ( empty( $item ) ) {
unset( $arr[$key] );
break;
}
}
}
Cheers
Upvotes: 1
Reputation: 1931
Use this code:
$source = array(
array('a', 'b', 'c', 'd'),
array('d', '_', 'b', 'a'),
array('a', 'b', '_', '_'),
array('d', 'c', 'b', 'a'),
array('_', 'b', 'c', 'd'),
array('d', 'c', 'b', 'a'),
);
$sourceCount = count($source);
for($i=0; $i<$sourceCount; $i++)
{
if(in_array("_", $source[$i])) unset($source[$i]);
}
Upvotes: 3
Reputation: 519
I would iterate through a foreach loop myself something like:
<?php
// Let's call our multidimensional array $md_array for this
foreach ($md_array as $key => $array)
{
$empty_flag = false;
foreach ($array as $key => $val)
{
if ($val == '')
{
$empty_flag = true;
}
}
if ($empty_flag == true)
{
unset($md_array[$key]);
}
}
?>
There's almost definitely a more efficient way of doing this so anyone else who has a better solution feel free to let me and Alex know.
Upvotes: 1
Reputation: 360702
$arr = array(... your multi dimension array here ...);
foreach($arr as $idx => $row) {
if (preg_grep('/^$/', $row)) {
unset($arr[$idx]);
}
}
Upvotes: 7
Reputation: 36466
Loop through the multidimensional array and check to see if the array at position i
contains any empty elements. If it does, call unset($arr[i])
to remove it.
for($i=0,$size=sizeof($arr); $i < $size; $i++) {
if( in_array( "", $arr[$i] ) )
unset( $arr[$i] );
}
Upvotes: 1