Skip to content
Advertisement

Skipping an index in foreach loop

I’ve seen options for only hitting certain numbers in a foreach (if i < 25, etc) but I’m wondering how to best skip a string index completely

I have a loop that works perfectly and I don’t want to change what it’s doing, I just want to omit one row that has the index of ’employee’

I’ve tried the below but it doesn’t seem to work as I get a syntax error at my if statement

foreach ($arr as $row) {
  if($arr[] !== 'employee'){
        for ($i = 0; $i < count($colstrs); $i++) {
            $cellstr = $colstrs[$i] . $xrow;
            $ows->setCellValue($cellstr, $row[$i]);
            $ows->getStyle($cellstr)->getNumberFormat()->setFormatCode($this->numfmt);
        }
        $this->setFillColors($xrow);            
        $xrow++;
   }
}

Advertisement

Answer

Considering you want to leave the loop body in tact, here is one possible non-destructive approach. Not checking anything on every iteration also saves you a little bit of performance loss. See comments for step-by-step explanation.

<?php

// Sample array. We'll be filtering out the first element ('a').
$a = ['a' => 123, 'b' => 2, 'c' => 'foo', 'd' => 'bar', 'abc' => 'def', 'def' => 789];

// Use array_filter() to copy the array on certain condition ($key !== 'a').
// Passing ARRAY_FILTER_USE_KEY will only pass the key to the callback, saving some memory.
// The original array is left untouched.
foreach (
    array_filter($a, function($key) { return $key !== 'a'; }, ARRAY_FILTER_USE_KEY)
    as $element
)
{
    var_dump($element);
}

/* Outputs:
int(2)
string(3) "foo"
string(3) "bar"
string(3) "def"
int(789)
*/
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement