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?
-
Why do you need to loop both arrays at the same time?Cyclonecode– Cyclonecode2012-01-13 19:08:31 +00:00Commented Jan 13, 2012 at 19:08
-
1Will they have the same number of elements?jprofitt– jprofitt2012-01-13 19:09:53 +00:00Commented Jan 13, 2012 at 19:09
Add a comment
|
5 Answers
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];
}
1 Comment
capi
nice solution with the keys mapping, +1
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
2 Comments
capi
never use a function inside a for condition, it will execute it each loop, your example should be instead : for ($i = 0, $max = sizeof($array); $i < $max; $i++)
martinstoeckli
That's what the
for loop is for. I would add the {...}, so one can see that you access the arrays from inside the loop.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++;
}
1 Comment
capi
if you're using a while loop, define the counts beforehand as variables, no need to do the count each loop (same as the post below), use while ($i<$max1 && $i<$max2) and define $max1 = count($ar1) and same for ar2 before the while loop
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);
}
?>