Search code examples
phpmultidimensional-arrayforeachunset

Difficulty deleting record from array within a foreach of the array


So I have an multidementional array, $lines, that was generated from a csv file. Its populated with records that look like the following:

 [0] => 038572 
 [1] => L 
 [2] => Testing
 [3] => BQ
 [4] => 
 [5] => 52.40308886
 [6] => -0.19266809
 [7] => 01/12/2018
 [8] => 
 [9] => B
 [10] => 
 [11] => 5
 [12] => 
 [13] => 
 [14] => 
 [15] => 
 [16] => ldn d 5BQ
 [17] => 038572
 [18] =>

I also have records which are all empty accept for one bit which has:

[16] => ,

Its these records that I'm trying to unset. So I tried the following:

foreach($lines as $element) {
    if ($element[16] == ",") {
        unset($element);
    }
}

But when I print_r the array $lines, I can still see those partially empty records.


Solution

  • You're working on a temporary copy inside your loop, so when you unset $element, it has no effect on the original $lines array. You can use references, or unset the value from the original array:

    foreach ($lines as $index => $element) {
        if ($element[16] === ',') {
            unset($lines[$index][16]);
        }
    }
    

    Or something like this:

    for ($i = 0, $_i < count($lines); $i < $_i; $i++) {
        if ($lines[$i][16] === ',') {
            unset($lines[$i][16]);
        }
    }
    

    Or any of a dozen other ways to do the same...

    Note, using unset() here will actually remove the item from the array, which may misalign your columns depending on how you have your code written. Instead of unsetting it, you may want to set it to null.