tags:

views:

225

answers:

4

Is there a way of iterating through an array but performing an operation on every other element? ie If I have an array with 13 elements how do I do something to only elements 2,4,6,8,10 and 12?

+1  A: 
for ($i=1; $i<sizeof($array); $i+=2) {
  // do stuff to $array[$i]
}

You can integrate it into a foreach loop too:

$i = 0;
foreach ($array as $v) {
  if ($i++ & 1) continue;
  // do stuff to $v
}

Note: $i & 1 is equivalent to ($i % 2) == 1 (or just $i % 2).

cletus
should the last part of the statement be $i+=2?
musoNic80
not sure I get the foreach example. Could you explain it to me a bit simpler?!
musoNic80
cletus
You should not put sizeof($array) in the loop condition. This will evaluate the size of $array N+1 times where N is the number of loops.
OIS
+1  A: 
foreach($array as $val) {
  if(($i++ % 2) == 0) {
    ...do stuff here...
  }
}
Phil Carter
This is how I'd do it, well except for the braces. The logic is dead simple and this reflects that nicely plus it makes it easy to extend with an else without rewriting the loop logic.
Kris
Answers are great, thanks. Can I add a real world example?I have an array which has an 2 elements for each day of the week. (Numbering beginning at 0). I want a loop that will do something on each DAY not on each element. How can I use the answers you've given to achieve this? PS There's no code yet to post, I'm just trying to work it out first!!!
musoNic80
if your array looks similar too$array = array('mon1', 'mon2', 'tue1', 'tue2' ... 'fri2'); and always follows a distinct pattern, then you can use that code as it's written. If you wanted to make sure it hit every day, you'd need to validate it somehow. It's hard to say without really knowing whats going in and what you want out.
Phil Carter
A: 

to fix cletuses answer for more speed and fix typos:

for ($i = 1, $j = count($array); $i < $j; $i += 2) {
    // code
}
Ozzy
Learnt something from this, I didn't know you could assign more than one variable in the first expression (or subsequent ones). Thanks!
Phil Carter
Speed? At best "caching" the array size is micro-optimization. It's also semantically equivalent. What if the array size changes during the loop?
cletus
@phil, np. glad to help :)@cletus, if your array changes during the loop, you should use a foreach or update $j in the loop. It is a speed optimisation and a valid one. Imagine an array of 1000000 values then youl see what i mean.
Ozzy
A: 

Another variation on the answers already posted... Similar to Phil Carter's answer. If the array has a numeric index you can use that in the foreach instead of managing a separate counter variable:

foreach ($array as $i => $v) {
  if (! ($i % 2)) {
  // do stuff to $v
}
dellsala