Dio
Dio

Reputation: 13

Unset data in a multidimensional array

I have csv[ ][ ]. How do I use a for each loop to unset data in rows?

for each ($index) {
if (conditions to meet) { 
unset(csv[$index]);     
}
}

Upvotes: 1

Views: 2394

Answers (2)

VolkerK
VolkerK

Reputation: 96159

http://docs.php.net/manual/en/control-structures.foreach.php says:

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

That's what you should use to modify single elements of the rows when using two foreach loops.

<?php
$csv = [
    [1,2,3,4,5],
    [2,3,4,5,6],
    [3,4,5,6,7],
    [4,5,6,7,8],
];

// make $row a reference
// so that unset($row[...]) affects $csv and not only a "copy".
foreach( $csv as &$row ) { 
    foreach( $row as $key=>$column ) {
        if ( 0===$column%2 ) { // e.g. remove all even elements
            unset( $row[$key] );
        }
    }
}

var_export($csv);

prints

array (
  0 => 
  array (
    0 => 1,
    2 => 3,
    4 => 5,
  ),
  1 => 
  array (
    1 => 3,
    3 => 5,
  ),
  2 => 
  array (
    0 => 3,
    2 => 5,
    4 => 7,
  ),
  3 => 
  array (
    1 => 5,
    3 => 7,
  ),
)

Or (same output) without foreach loops.

<?php
$csv = [
    [1,2,3,4,5],
    [2,3,4,5,6],
    [3,4,5,6,7],
    [4,5,6,7,8],
];

$csv = array_map(
    function($row) {
        return array_filter(
            $row,
            function($col) {
                return 0!==$col%2; 
            }
        );
    },
    $csv
);

var_export($csv);

Upvotes: 0

EL OUFIR Hatim
EL OUFIR Hatim

Reputation: 419

Try this :

foreach ($csv as $key => $value) {
        unset($csv[$key]);
    }

Upvotes: 1

Related Questions