Home > Software design >  How to Count Skipped Items in PHP array
How to Count Skipped Items in PHP array

Time:07-20

lets suppose that I have an Array;

$array = [1, 2, "Mohcin", "Mohammed", 3,];

I can Access this array and skip the items "Mohcin" and "Mohammed" inside the iteration using for or foreach loop and continue.. but my question how I can count the number of items that I skipped inside the loop? and that is "TWO" in this case.

Thanks in advance

CodePudding user response:

$array = [1, 2, "Mohcin", "Mohammed", 3,];
$skipped = 0;

foreach ($array as $element) {
    if ($someCondition) {
        // Remove the element
        $skipped  ;
    }
}

// You access $skipped here

CodePudding user response:

You can do it even without a foreach loop.

$array = [1, 2, "Mohcin", "Mohammed", 3,];
$skip = ["Mohcin", "Mohammed"];
$diff = array_diff($array, $skip);
$skipCount = count($array) - count($diff);

But if you want with foreach for the reason of more complex logic, do like this

$skipCount = 0;
foreach($array as $value) {
    if($value === "Mohcin" || $value === "Mohammed") {
        $skipCount  ;
        continue;
    }
    // Do anything else when not skipped
}

CodePudding user response:

You need to create variable that keeps count of skips every time you skip value.

$skips = 0;
for($counter = 0; $counter < count($array); $counter  ) {
    if(skip) {
         $skips  ;
         continue;
    }
}
  • Related