user1049944
user1049944

Reputation:

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.

It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:

  1. No
  2. Yes
  3. No
  4. No
  5. No
  6. Yes
  7. No
  8. No
  9. No
  10. Yes
  11. No
  12. No

I have the following foreach() loop which is similar to what I need:

$count = 1;

foreach($_POST['input_7'] as $val) {        
if ($count % 2 == 0) {
        echo $val;
        echo '<br>';
    }

    $count ++;
}

However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.

Is it possible for me to amend my loop to match that what I need?

Upvotes: 0

Views: 891

Answers (2)

h2ooooooo
h2ooooooo

Reputation: 39532

You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:

for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
    echo $_POST['input_7'][$i] . '<br />';
}

Example:

<?php
    $array = array(
        'foo1', 'foo2', 'foo3', 'foo4', 'foo5', 
        'foo6', 'foo7', 'foo8', 'foo9', 'foo10', 
        'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
    );

    for ($i = 1; $i < count($array); $i += 4) {
        echo $array[$i] . '<br />';
    }
?>

Output:

foo2
foo6
foo10
foo14

DEMO

Upvotes: 3

Michael Helwig
Michael Helwig

Reputation: 530

Try this:

$count = 3;

foreach($_POST['input_7'] as $val) {

    if ($count % 4 == 0) {
        echo $val;
        echo '<br>';
    }

    $count ++;
}

Upvotes: 0

Related Questions