R Peter
R Peter

Reputation: 15

Displaying Image with same sizes every alternate rows PHP

I am showing the images and getting all that images from database. I'm showing two images on one row, in which the first image is big in size while the second one is small in size. Now the 2nd row again have the two images but this time first image should be small and the second should be large.

I am using PHP and used 'foreach' for loop to get all the images form the database. So how can I do this ? here is a sample piece of code:

 <? foreach ($model->images as $img) { ?>
     <div class="big_img">
         <div class='list_img' style="background-image: url('<?= $img->url ? : UPLOAD_URL.'images/'.$img->image1?>')">
     </div>

     <div class="small_img">
         <div class='list_img' style="background-image: url('<?= $img->url ? : UPLOAD_URL.'images/'.$img->image2?>')">
     </div>
 <? } ?>

Upvotes: 1

Views: 47

Answers (3)

Dale
Dale

Reputation: 10469

And just for the sake of it...

You can even (no pun intended) use bitwise operations..

<?php

$index = 0;
foreach($things as $thing) {
    if( ++$index & 1 ) {
        // $index is odd
    } else {
        // $index is even
    }
}

?>

Upvotes: 0

FirstOne
FirstOne

Reputation: 6215

You could have a variable and flip it each time:

<?
$cont = true;
foreach ($model->images as $img) { ?>
    <div class="<?php echo $cont ? 'big_img' : 'small_img'; ?>">
        <div class='list_img' style="background-image: url('<?= $img->url ? : UPLOAD_URL.'images/'.$img->image1?>')">
    </div>

    <div class="<?php echo !$cont ? 'small_img' : 'big_img'; ?>">
        <div class='list_img' style="background-image: url('<?= $img->url ? : UPLOAD_URL.'images/'.$img->image2?>')">
    </div>
<? $cont = !$cont; } ?>

So, basically, when the variable is true, display big-small and when it's false, small-big. Each iteration you negate the variable, meaning when it's true, it will become false and vice-versa.

Upvotes: 1

puelo
puelo

Reputation: 6037

You could use the modulo operator to determine what the order of the two sizes should be. Something along these lines (untested and very crude):

<? $index = 0; foreach ($model->images as $img) { ?>
     <div class="<? echo $index % 2 == 0 ? : 'big_img' : 'small_img'; ?>">
         <div class='list_img' style="background-image: url('<?= $img->url ? : UPLOAD_URL.'images/'.$img->image1?>')">
     </div>

     <div class="<? echo $index % 2 == 0 ? : 'small_img' : 'big_img'; ?>">
         <div class='list_img' style="background-image: url('<?= $img->url ? : UPLOAD_URL.'images/'.$img->image2?>')">
     </div>
 <? $index++; } ?>

Upvotes: 0

Related Questions