fr3d
fr3d

Reputation: 685

PHP counter doesn't work

I created a short code, where the counter is used to count up the elements, but the counter counts only till "1", why?

<?php $counter = "0";?>
<?php foreach($this->group('inhalt') as $i => $fields): ?>
    <?php $counter += 1 ;?>
    <div class="ce_countup autogrid-id_<?php echo $this->id; ?>_<?php echo $counter;?> autogrid-type_cte <?php if($counter ="1"){ echo "autogrid-first";} ?> <?php if($counter =$gridKlasse){ echo "autogrid-last";} ?> <?php echo $gridKlasse;?> autogrid_mode_auto autogrid block">
        <h3 id="ce_id_<?php echo $this->id; ?>_<?php echo $counter;?>"><?php echo $this->field('zahl#'.$i)->value(); ?></h3>
        <?php echo $this->field('bezeichnung#'.$i)->value(); ?>
    </div>   
<?php endforeach; ?>

Upvotes: 0

Views: 119

Answers (1)

motanelu
motanelu

Reputation: 4025

Your problem is here

<?php if($counter ="1"){ echo "autogrid-first";} ?>

and here

<?php if($counter = $gridKlasse){ echo "autogrid-last";} ?>

You're always re-initializing the $counter variable with 1 and then doing a boolean evaluation of the whole expression. You should use either == or === to fix the problem. Also, $gridKlasse should be a number.

Try this:

<?php $counter = 0;?>
    <?php foreach($this->group('inhalt') as $i => $fields): ?>
    <?php $counter += 1 ;?>
    <div class="ce_countup autogrid-id_<?php echo $this->id; ?>_<?php echo $counter;?> autogrid-type_cte <?php if($counter === 1){ echo "autogrid-first";} ?> <?php if($counter === $gridKlasse){ echo "autogrid-last";} ?> <?php echo $gridKlasse;?> autogrid_mode_auto autogrid block">
        <h3 id="ce_id_<?php echo $this->id; ?>_<?php echo $counter;?>"><?php echo $this->field('zahl#'.$i)->value(); ?></h3>
        <?php echo $this->field('bezeichnung#'.$i)->value(); ?>
    </div>   
<?php endforeach; ?>

Upvotes: 3

Related Questions