directory
directory

Reputation: 3167

php foreach even and odd but vice versa after printing 2 rows

In my application I have to loop images with two sizes. Lets call them large and small.. These images are in two columns like below.

large small
large small
large small

I produce the larage/small image by a class by doing this now like this:

<?php $count = 0; ?>
<?php foreach ($posts as $post) : ?>
<div class=" <?=(++$count%2 ? "col-7 pr-10" : "col-5 pl-10");?> mt-15">
<?php endforeach; ?>

What I would like to do here by now is to produce this list;

large small
small large
large small
etc..

In what kind of way can I do this? I guess I have to create a kind of reset after each 2 entries and set odd to eve and vise versa ?

Upvotes: 0

Views: 156

Answers (3)

CMPS
CMPS

Reputation: 7769

<?php $count = 0; $flag = 0;?>
<?php foreach ($posts as $post) : ?>
<?php $flag = $count%2 == 0 ? $flag + 1 : $flag;?>
<div class=" <?=(($count++ +$flag)%2 ? "col-7 pr-10" : "col-5 pl-10");?> mt-15">
<?php endforeach; ?>

Upvotes: 0

Floris
Floris

Reputation: 46375

In general if you need A B; B A; A B; etc in consecutive loops, you could do this:

$row = 0;
foreach ($posts as $post) {
  if ($row%2) echo "A, B\n"; else echo "B, A\n";
  $row++;
}

This looks quite a bit like your code…

If instead you really mean that you need to do

A
B
B
A

(pattern repeating every 4th row, in essence), then a clear and reasonable approach is:

$row = 0;
foreach ($posts as $post) {
  $temp = $row%4;
  if ($temp == 0 || $temp == 3 ) echo "A\n"; else echo "B\n";
  $row++;
}

This can obviously be made more compact - but I usually find that "explicit" is easier to read six months later - and the performance impact is negligible.

Upvotes: 1

RobP
RobP

Reputation: 9522

Try replacing

<div class=" <?=(++$count%2 ? "col-7 pr-10" : "col-5 pl-10");?> mt-15">

with

<div class=" <?=($count%4 == 1 || ? $count%4 == 2)"col-7 pr-10" : "col-5 pl-10"; $count++;?> mt-15">

Upvotes: 0

Related Questions