user3352340
user3352340

Reputation: 145

foreach() every 4 change output

I have an issue where I don't know for a foreach() loop to change the output on every(x) amount of results.

Here is my foreach() code:

$dir_handle = 'assets/icons/';
    foreach(array_diff(scandir($dir_handle), array('.', '..')) as $file) {
        $cut = substr($file, -4);
        echo '<a href="action.php?do=changeicon&set=' . $cut . '"><img id="preload_header" src="assets/icons/' . $file . '" /></a><br />';
}

How would I get it for that 1-4 have the same result, but then 5-8 have a different result, and then back to 1-4?

Upvotes: 1

Views: 163

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74625

You can use the % operator, combined with a division by 4:

foreach ($a as $key => $val) {
    $phase = $key / 4 % 2;
    if ($phase === 0) {
        echo 'here';
    }
    elseif ($phase === 1) {
        echo 'there';
    }
}

This switches between the two branches every 4 iterations of your loop.

As pointed out in the comments, the above method assumes that the keys of your array are in order. If not, you can add a counter variable in the loop, like:

$c = 0;
foreach ($a as $val) {
    $phase = $c++ / 4 % 2;
    if ($phase === 0) {
        echo 'here';
    }
    elseif ($phase === 1) {
        echo 'there';
    }
}

Upvotes: 0

Pattle
Pattle

Reputation: 6016

You want to do a count in your foreach loop

$count = 1;
foreach(array_diff(scandir($dir_handle), array('.', '..')) as $file) {
    //Check if count is between 1 and 4
    if($count >= 1 && $count <= 4) {

        //Do something

    } else { //Otherwise it must be between 5 and 8

        //Do something else

        //If we are at 8 go back to one otherwise just increase the count by 1
        if($count == 8) {
            $count = 1;
        } else {
            $count++;
        }
    }
}

Upvotes: 1

Related Questions