John Davidson

php - Skipping an index in foreach loop

0 comments
Message:


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++;
}
}


My Answer:
You can use the `continue` statement to skip a specific index in the foreach loop. Here's how you can modify your code to skip the row with the index 'employee':

php
foreach ($arr as $row) {
if($row === 'employee'){
continue;
}

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++;
}


In this code snippet, the `continue` statement is used to skip the current iteration of the loop if the value of `$row` is 'employee'. This way, the row with the index 'employee' will be omitted from the loop.

Rate this post

3 of 5 based on 1828 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us