2

I am sure I am making this way more complicated than it is...

I have an array of values, lets just say they are numbers for now. I want to display them on a page in 3 columns. So I made 3 loops, one for each column. The first loop I want to loop every 3rd value, starting at index 0. The second loop should start at index 1 and do every third. And the third loop should start at index 2 and loop through every third.

This is what I wrote, which seems to work if you only have 3 things in the array, and I'm sure it's overly complicated.

Thanks

 <div class="span4 column">
        <?php for ($i = 0; $i <= count($articles_for_board)/3; $i = $i+2):?>
            stuff in here
            </div>
        <?php endfor; ?>
    </div>
    <div class="span4 column">
        <?php for ($i = 1; $i <= (count($all_boards)/3)+1; $i = $i+2):?>
            stuff in here
            </div>
        <?php endfor; ?>
    </div>
    <div class="span4 column">
        <?php for ($i = 2; $i <= (count($all_boards)/3)+2; $i = $i+2):?>
            stuff in here
            </div>
        <?php endfor; ?>
    </div>

So basically, the first column would hold array index 0, 3, 6... second column would hold 1, 4.. etc third column would hold 2, 5, 8...

THanks

3
  • There are too many </div> tags in your code. Is it normal? Commented Aug 21, 2012 at 1:26
  • The question is, how do i make a loop that loops through every 3rd element in an array... I'm sure i'm just having a brain fart, but nothhing I'm doing is working Commented Aug 21, 2012 at 1:29
  • $i += 3 at the end of the loop is the complete answer. You didn't need to divide the length or add anything to the length in the termination condition. Commented Aug 21, 2012 at 1:30

1 Answer 1

4

With a for-loop, you don't need to worry so much about all that bounds checking. It's a lot simpler than you think it is:

for ($i = 0; $i < count($all_boards); $i += 3)

This loop increments by three every iteration — that is, it gets every third member — and it stops as soon as it exceeds the length of $all_boards.

Sign up to request clarification or add additional context in comments.

2 Comments

To finish answering the question: start the second loop at $i = 1, and the third with $i = 2, and you have your 3 loops that don't repeat any values.
Thanks... yea I was thinking too hard about it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.