sledgeweight
sledgeweight

Reputation: 8095

Incrementing with for in while loop results in 0

Why won't $i count up one each time with the following code?

<?php if(get_field('staff_member')) { ?>
    <div class="row-fluid">
        <?php while(has_sub_field('staff_member')) 
        {
        for($i = 0; $i <= 1;  $i++)
        echo '<div class="span3 mobile_width' . $i . '"> 

    .....etc...
}
echo '</div>';
}
?>

The output has 4 items and they all return with the the class mobile_width0.

And it also outputs 2 of each item.

Upvotes: 0

Views: 113

Answers (4)

RiceRiceBaby
RiceRiceBaby

Reputation: 1596

because your resetting "i" to 0 in your for loop.

Upvotes: 0

Marko D
Marko D

Reputation: 7576

Because you are resetting it to 0 each time. You don't need for loop, that's why you had double output. You can do it like this:

<?php $i = 0; 
    while(has_sub_field('staff_member')) {
        echo '<div class="span3 mobile_width' . $i . '">';
        $i++;
    }

Upvotes: 1

Mollo
Mollo

Reputation: 723

Each time your while cicle iterates, $i gets reset to 0 and in this line for($i = 0; $i <= 1; $i++) you are saying that $i just can take 0 and 1 values

Upvotes: 0

yunzen
yunzen

Reputation: 33439

Try

for($i = 0; $i < 1; $i++)

< instead of <=

Upvotes: 0

Related Questions