I'm new to PHP. I have two arrays $array1
and $array2
of equal size. I've been using foreach
loops to iterate through arrays like so:
foreach($array1 as $element1) {
//Do stuff with $element1
}
and
foreach($array2 as $element2) {
//Do stuff with $element2
}
but now I'd like to iterate through both arrays at the same time so that I have access to both $element1
and $element2
in the loop body.
How do I do that?
while (($element1 = next($array1)) !== false) {
$element2 = next($array2);
// Do something
}
But it will fail, if false
is an allowed value in $array1
. If (in this case) false
is not allowed in $array2
, you can just swap both
A "foreach"-solution (if both shares the same key)
foreach ($array1 as $i => $element1) {
$element2 = $array2[$i];
// Do something
}
A third (I think quite nice) solution, that just allows primitive types in $array1
foreach (array_combine(array_values($array1), array_values($array2)) as $element1 => $element2) {
// Do something
}
Each returns an array containing the key and value, and advances the pointer to the next element. It returns false once it has advanced past the last element.
// Iterate until one of the arrays is complete
while (($a = each($array_a)) !== false && ($b = each($array_b)) !== false) {
echo "The key:value from array_a is {$a['key']}:{$a['value']}.\n";
echo "The key:value from array_b is {$b['key']}:{$b['value']}.\n";
}
To iterate completely over both arrays, use || instead of &&.
use a for loop instead...
for($i = 0;$i<count($array1);$i++) {
/* access $array1[$i] and $array2[$i] here */
}
This will work if the indexes of the arrays are numeric and the same for both arrays
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With