Elaine Byene Elaine Byene - 3 months ago 7
PHP Question

Add a dynamic sequence number in a DIV class using PHP

This is a PHP version which repeats the DIVs. I want to add a dynamic class to the ClassX. X being a dynamic sequence number. Something like Class1, Class2, etc..

<div class="row">
<?php foreach ($this->fields as $field) { ?>
<div class="col-sm-5 col-xs-12 ClassX">
<?php echo $field[0]; ?>
</div>
<div class="col-sm-6 col-xs-12">
<?php echo $field[1]; ?>
</div>
<?php } ?>
</div>


The Output to be something like this:

<div class="row">
<div class="col-sm-5 col-xs-12 Class1">text</div>
<div class="col-sm-6 col-xs-12">text</div>
<div class="col-sm-5 col-xs-12 Class2">text</div>
<div class="col-sm-6 col-xs-12">text</div>
<div class="col-sm-5 col-xs-12 Class3">text</div>
<div class="col-sm-6 col-xs-12">text</div>
<div class="col-sm-5 col-xs-12 Class4">text</div>
<div class="col-sm-6 col-xs-12">text</div>
</div>


How do I add that class to change dynamically in a sequence?

Answer

here you go <?= ++$n is similar to <?php echo ++$n; and you don't need short tags enabled

<div class="row">
    <?php $n=0; foreach ($this->fields as $field) { ?>
        <div class="col-sm-5 col-xs-12 Class<?= ++$n ?>">
            <?= $field[0]; ?>
        </div>
        <div class="col-sm-6 col-xs-12">
            <?= echo $field[1]; ?>
        </div>
    <?php } ?>
</div>
Comments