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, _, _
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]);
}
See: http://ideone.com/Vfd6Z
$arr = array(... your multi dimension array here ...);
foreach($arr as $idx => $row) {
if (preg_grep('/^$/', $row)) {
unset($arr[$idx]);
}
}
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] );
}
Try this:
Note: $arr is your array.
foreach ( $arr as $key => $line ) {
foreach ( $line as $item ) {
if ( empty( $item ) ) {
unset( $arr[$key] );
break;
}
}
}
Cheers
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.