Use two loops:
foreach ($products as $product) {
foreach ($categories as $category) {
// using $product and $category
}
}
I had the same question today as the OP. I figured I can split up the problem by first merging the two arrays and then performing the actual foreach loop on the combined array.
This is the idea:
$combined_array = $products + $categories
foreach ($combined_array as $items) {. . .}
Practically speaking, I split the problem into two foreach loops, the first for the merging of the arrays and the second for the actual algorithm.
And indeed it does save me alot of space! Since it is much shorter to append one array to another array than to repeat a complicated foreach algorithm on two separate arrays consecutively.
If your two arrays have the same length, just use a for loop instead and access the elements using the current index.
You just have to make sure, that the indezies are matching in the two arrays.
Its not possible to achieve what you are trying using a foreach loop.
for ($i = 0; $i < count($arr1); $i++) {
// do whatever you want with $arr1[$i] and $arr2[$i]
}
If your array have the same length, but the indizies may differ and you still want them to be on par, use array_values()
before the loop to reindex both arrays.
This will only work for index based arrays!