0

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?

2
  • Do you have to use foreach or can you use a for loop? Commented Dec 22, 2013 at 19:38
  • Not necessarily, I was just thinking that would be the only way to loop through the array? For loop would be fine too I imagine! Commented Dec 22, 2013 at 19:39

2 Answers 2

3

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

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

3 Comments

@pealo86 Just be aware of the fact that your array MUST have at least 2 items, or this will bug out. :) If it sometimes won't, surround it by a check for count() and have it be >= 2.
Thanks, by this do you mean the $_POST['input_7'] array? If so, this will always have at least 4 items I believe :)
@pealo86 Yes - as it starts on position 1 (value #2) then it needs minimum 2 values. :)
0

Try this:

$count = 3;

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

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

    $count ++;
}

1 Comment

You should prefer h2ooooooo's solution if you don't need to keep the foreach loop.

Your Answer

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