Andy Chan
Andy Chan

Reputation: 93

PHP foreach iterate twice instead of once

I have a question regarding the foreach function in php:

At the moment I have:

<html>
<body>

<?php

$x=array("one","two","three", "four", "five", "six", "seven", "eight"); 

foreach ($x as $value)
  {
    echo $value . "<br />";
  }
?>

Which outputs:

one
two
three 
four
five
six
seven
eight

But how do I make a foreach loop iterate twice instead of once so that I get:

two
four 
six 
eight

Is this even possible? Or is it better to just use a for loop instead?

Any help will be appreciated, thank you.

Upvotes: 0

Views: 1693

Answers (6)

Logan Serman
Logan Serman

Reputation: 29870

Do you mean to step over every other entry? You should just use a for loop:

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

Upvotes: 4

Brijesh
Brijesh

Reputation: 1

<?php

$x=array("one", "two", "three", "four", "five", "six", "seven", "eight"); 
$i=2;
foreach ($x as $value) {
     if( ($i % 2)==0 ) {
        echo $value . "<br />";
     }
    $i++;
  }
?>

Upvotes: 0

ajreal
ajreal

Reputation: 47321

$cnt = 0;
foreach ($x as $value)
{
  $cnt++;
  if ($cnt % 2 == 1) continue;
  echo $value . "<br />";
}

I would like to bring this for @GordonM
using for is only work assuming the array is in sequential index order,
an array such as

 array(2=>'one', 1=>'two', 4=>'three' ...)

will drag you to hell

Upvotes: 1

Pete
Pete

Reputation: 635

<?php
    $i=1;

    $x=array("one","two","three", "four", "five", "six", "seven", "eight"); 

    foreach ($x as $value) {
        $i++;
        if($i%2==0){
          continue;
        }
      echo $value . "<br />";
    }
  ?>

Upvotes: 3

Lobo
Lobo

Reputation: 4147

Perhaps this is what you want.

$t=count($x);
for($i=0;$i<$t;$i++){
   if($i%2==0 && $i>0){
      echo $x[$i]."<br>";
   }
}

Regards!

Upvotes: 1

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146430

If by "iterate twice" you mean "skip odd entries":

$odd = FALSE;
foreach ($x as $value)
{
    $odd = !$odd;
    if($odd){
        continue;
    }

    echo $value . "<br />";
}

(If you choose to use foreach you need to count yourself.)

Upvotes: 2

Related Questions