Anay Bose Anay Bose - 2 months ago 17
PHP Question

Manipulating styles in a php for loop

I am trying to add some styles to some divs in a php for loop. For each alternative iteration the position style is set either

'left: 0%' or 'left:53.8462%'
, which seems to be working. But I can't figure out how to set the top style. For each consecutive
two iterations
the value of the top style is increased by
342px
while the initial value is set to 0px. In other words, for the first and second loop, top style value is 0px, but in the second and third iteration their values are incremented by 342px and so forth. The desired html output is shown below.

In the following code this part
echo ($counter % 6 == 1 ? 'top: 0px;' : 'top: 342px;');
needs to changed.

<?php $counter = 1; ?>
<?php for ($i = 0; $i < 4; $i++): ?>
<div class="card" style="position: absolute;
<?php echo ($i%2 ? 'left: 53.8462%;' : 'left: 0%;'); echo ($counter % 6 == 1 ? 'top: 0px;' : 'top: 342px;');?>">

// content //

<?php $counter++; ?>
<?php endfor;
?>


Here is the desired html output:

<div class="card" style="position: absolute; left: 0%; top: 0px;">

</div>

<div class="card" style="position: absolute; left: 53.8462%; top: 0px;">

</div>

<div class="card" style="position: absolute; left: 0%; top: 342px;">

</div>

<div class="card" style="position: absolute; left: 53.8462%; top: 342px;">

</div>

<div class="card" style="position: absolute; left: 0%; top: 684px;">

</div>

<div class="card" style="position: absolute; left: 53.8462%; top: 684px;">

</div>

Answer

It would be easier if you started $counter at 0. Then the top is just half of the counter multiplied by 384.

And in this case, $counter is the same as $i, so there's no need for two variables.

<?php for ($i = 0; $i < 4; $i++): ?>
<div class="card" style="position: absolute; 
    <?php echo ($i%2 ? 'left: 53.8462%;' : 'left: 0%;'); echo 'top: ' . floor($i/2)*384 . 'px;';?>">

    // content //

    <?php endfor;
?>