user1110597
user1110597

Reputation: 77

php foreach loop

I have two arrays in my code. Need to perform a foreach loop on both of these arrays at one time. Is it possible to supply two arguments at the same time such as foreach($array1 as $data1 and $array2 as $data2) or something else?

Upvotes: 2

Views: 201

Answers (5)

tcables
tcables

Reputation: 1307

Dont use a foreach. use a For, and use the incremented index, eg. $i++ to access both arrays at once.

Are both arrays the same size always? Then this will work:

$max =sizeof($array);
for($i = 0; $i < $max; $i++)

array[$i].attribute
array2[$i].attribute

If the arrays are different sizes, you may have to tweak your approach. Possibly use a while.

iterative methods:

http://php.net/manual/en/control-structures.while.php

http://php.net/manual/en/control-structures.for.php

http://php.net/manual/en/control-structures.do.while.php

Upvotes: 1

Lepidosteus
Lepidosteus

Reputation: 12047

Assuming both have the same number of elements

If they both are 0-indexed arrays:

foreach ($array_1 as $key => $data_1) {
  $data_2 = $array_2[$key];
}

Otherwise:

$keys = array_combine(array_keys($array_1), array_keys($array_2));

foreach ($keys as $key_1 => $key_2) {
  $data_1 = $array_1[$key_1];
  $data_2 = $array_2[$key_2];
}

Upvotes: 2

Tamer Shlash
Tamer Shlash

Reputation: 9523

No to my knowledge with foreach, but can be easily done with for:

<?php

$cond1 = 0<count($array1);
$cond2 = 0<count($array2);

for ($i=0;$cond1 || $cond2;$i++)
{
    if ($cond1)
    {
        // work with $array1
    }
    if ($cond2)
    {
        // work with $array2
    }
    $cond1 = 0<count($array1);
    $cond2 = 0<count($array2);
}

?>

Upvotes: 0

shox
shox

Reputation: 1160

use for or while loop e.g.

$i = 0; 
while($i < count($ar1) && $i < count($ar2)  ) // $i less than both length ! 
{ 
  $ar1Item = $ar1[$i];
  $ar2Item = $ar2[$i];

  $i++;
}

Upvotes: 0

gen_Eric
gen_Eric

Reputation: 227310

If they both the same keys, you can do this:

foreach($array1 as $key=>data1){
    $data2 = $array2[$key];
}

Upvotes: 2

Related Questions