How can I loop through two arrays at once?
Problem
Well the problem is of course your nested foreach loop. Because for each element of your $data1
array you loop through the entire $data2
array (So in total there are $data1
* $data2
iterations).
Solutions
To solve this you have to loop through both arrays at once.
array_map()
method (PHP >=5.3)
You can do this with array_map()
and pass all arrays to it which you want to loop through at the same time.
array_map(function($v1, $v2){
echo $v1 . "<br>";
echo $v2 . "<br><br>";
}, $data1, $data2 /* , Add more arrays if needed manually */);
Note: If the amount of elements are uneven you won't gen any errors, it will just print NULL
(Means you won't see anything)
MultipleIterator
method (PHP >=5.3)
Use a MultipleIterator
and attach as many ArrayIterator
as you need.
$it = new MultipleIterator();
$it->attachIterator(new ArrayIterator($data1));
$it->attachIterator(new ArrayIterator($data2));
//Add more arrays if needed
foreach($it as $a) {
echo $a[0] . "<br>";
echo $a[1] . "<br><br>";
}
Note: If the amount of elements are uneven it will just print all values where both arrays still have values
for loop
method (PHP >=4.3)
Use a for loop with a counter variable, which you can use as key for both arrays.
$keysOne = array_keys($data1);
$keysTwo = array_keys($data2);
$min = min(count($data1), count($data2));
for($i = 0; $i < $min; $i++) {
echo $data1[$keysOne[$i]] . "<br>";
echo $data2[$keysTwo[$i]] . "<br><br>";
}
Note: Using array_keys()
is just so that this also works if the arrays don't have the same keys or are associative. min()
is used to only loop through as many elements as every array has
array_combine()
method (PHP >=5.0)
Or if the arrays only have unique values, you can array_combine()
both arrays, so that $data1
can be accessed as key and $data2
as value.
foreach(array_combine($data1, $data2) as $d1 => $d2) {
echo $d1 . "<br>";
echo $d2 . "<br><br>";
}
Note: The arrays must have the same amount of elements, otherwise array_combine()
will throw an error
call_user_func_array()
method (PHP >=5.6)
If you want to print more than 2 arrays at the same time or just an unknown amount of arrays, you can combine the array_map()
method with a call_user_func_array()
call.
$func = function(...$numbers){
foreach($numbers as $v)
echo $v . "<br>";
echo "<br>";
};
call_user_func_array("array_map", [$func, $data1, $data2]);
Note: Since this kinda uses the array_map()
method, it behaves the same with uneven amount of elements. Also since this method only works for PHP >=5.6 you can just remove the arguments and change out $numbers
with func_get_args()
in the foreach loop and then it also works for PHP >=5.3
forEach loop through two arrays at the same time in javascript
Use the second parameter forEach
accepts instead, which will be the current index you're iterating over:
n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22];
n.forEach((element, index) => { console.log(element, index);});
How can I iterate through two arrays at the same time without re-iterating through the parent loop?
Use a normal for
loop instead of a foreach
, so that you get an explicit loop counter:
for($i=0; $i<count($content)-1; $i++) {
echo $content[$i].'-'.$contentb[$i];
}
If you want to use string based indexed arrays, and know that the string indexes are equal between arrays, you can stick with the foreach
construct
foreach($content as $key=>$item) {
echo $item.'-'.$contentb[$key];
}
Quick way to iterate through two arrays python
arr1 = [1,2,3,4,5]
arr2 = [4,5,6,7]
same_items = set(arr1).intersection(arr2)
print(same_items)
Out[5]: {4,5}
Sets hashes items so instead of O(n) look up time for any element it has O(1). Items inside need to be hashable for this to work. And if they are not, I highly suggest you find a way to make them hashable.
Loop through an two arrays simultaneously and pass a first element of each array to the function at a time using angular js [new to angular]
I'm guessing array1
and array2
are of same length. This should work.
var vm = { save: function(a, b) { console.log(a, b) }};vm.array1 = [{ id: 1}, { id: 2}, { id: 3}];vm.array2 = [{ id: 4}, { id: 5}, { id: 6}];
vm.array1.forEach(function(a1, i) { vm.save(a1, vm.array2[i]);});
What is the pythonic way to loop through two arrays at the same time?
If the lists a
and b
are short, use zip (as @Vincenzo Pii showed):
for x, y in zip(a, b):
print(x + y)
If the lists a
and b
are long, then use itertools.izip to save memory:
import itertools as IT
for x, y in IT.izip(a, b):
print(x + y)
zip
creates a list of tuples. This can be burdensome (memory-wise) if a
and b
are large.
itertools.izip
returns an iterator. The iterator does not generate the complete list of tuples; it only yields each item as it is requested by the for-loop. Thus it can save you some memory.
In Python2 calling zip(a,b)
on short lists is quicker than using itertools.izip(a,b)
. But in Python3 note that zip
returns an iterator by default (i.e. it is equivalent to itertools.izip
in Python2).
Other variants of interest:
- from future_builtin import zip -- if you wish to program with
Python3-stylezip
while in Python2. - itertools.izip_longest -- if
a
andb
are of unequal length.
Two arrays in foreach loop
foreach( $codes as $code and $names as $name ) { }
That is not valid.
You probably want something like this...
foreach( $codes as $index => $code ) {
echo '<option value="' . $code . '">' . $names[$index] . '</option>';
}
Alternatively, it'd be much easier to make the codes the key of your $names
array...
$names = array(
'tn' => 'Tunisia',
'us' => 'United States',
...
);
Related Topics
How to Extend Access Token Validity Since Offline_Access Deprecation
MySQLi: Can It Prepare Multiple Queries in One Statement
Insert/Update Helper Function Using Pdo
Encrypting/Decrypting File With Mcrypt
SQL Injections in Adodb and General Website Security
How to Upload Images into MySQL Database Using PHP Code
How Safe Are PHP Session Variables
How to Remove Accents and Turn Letters into "Plain" Ascii Characters
How to Get the File Extension in PHP
How to Get the Base Url With PHP
How to Post Json to PHP With Curl
PHP - Accessing Multidimensional Array Values