flux
flux

Reputation: 1648

PHP loop needs to be incremented by more than one each time. How can I exit out of the loop when condition is met?

I want to combine three php arrays by taking one entry and placing it underneath the other, like so:

while ($i <= $no)
{
        $results[$i] = $blah[$i];
        $i++;
        $results[$i] = $thing[$i];
        $i++;
        $results[$i] = $something[$i];
        $i++;
}

However the problem with this is $no can be exceeded as I need to increment $i three times in each loop.

End result:

array (size=12)
  1 => 
    array (size=4) (from $blah)
  2 => 
    array (size=4) (from $thing)
  3 => 
    array (size=4) (from $something)
  4 => 
    array (size=4) (from $blah)

...this needs to continue until the size of $no is met

Upvotes: 1

Views: 351

Answers (3)

phihag
phihag

Reputation: 288100

You're looking for the break statement. You may also want to append to the result array, instead of specifying a specific index:

$results = array();
while ($i <= $no) {
    $results[$i] = $blah[$i];
    $i++;
    if ($i > $no) break;
    $results[] = $thing[$i]; // just append
    $i++;
    if ($i > $no) break;
    array_push($results, $something[$i]); // append with array_push
    $i++;
}

Upvotes: 1

iambriansreed
iambriansreed

Reputation: 22251

Why not simplify:

$results = array_push($blah, $thing, $something);
// appends the arrays together

or

$results = array_merge($blah, $thing, $something);
// merges arrays together

Upvotes: -1

Mathlight
Mathlight

Reputation: 6653

simple tought, can't you do something like this???

   while ($i <= $no)
        {
                $results[$i] = $blah[$i];
                $i++;
                if($i > $no){ break;}
                $results[$i] = $thing[$i];
                $i++;
                if($i > $no){ break;}
                $results[$i] = $something[$i];
                $i++;
        }

Upvotes: 2

Related Questions