1

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]);     
}
}
1
  • foreach ($csv as $key => $value) { if (0 === strpos($csv[$key][0], 'bad')) { unset($csv[$key]); } } thank you :) Commented Jul 12, 2015 at 5:20

2 Answers 2

1

Try this :

foreach ($csv as $key => $value) {
        unset($csv[$key]);
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.