php looping through multiple arrays
If they have the same keys you can just loop through the keys and use them to index the arrays using array_keys
:
foreach(array_keys($array_one) as $key) {
// do something with $array_one[$key] and $array_two[$key]
}
If you're worried about some keys not existing you can try (e.g.) array_key_exists($key,$array_two)
. 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',
...
);
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 valuesfor 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 hasarray_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 errorcall_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 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
constructforeach($content as $key=>$item) {
echo $item.'-'.$contentb[$key];
}
How to loop through array of multiple arrays in php
Use the indexes of one of the sub-arrays to access all the other sub-arrays:
foreach ($array['item_id'] as $i => $item_id) {
$request_explanation = $array['request_explanation'][$i];
$quantity = $array['quantity'][$i];
// repeat this for all the columns
// Now you can insert all these variables into the database
}
How to loop through multiple arrays at the same time (parallel)
Since you said that all arrays match by their keys, I will assume you have something like this:
$article_ids = [10, 22, 13];
$article_descriptions = ["this is one", "this is two", "this is three"];
$article_amounts = [20, 10, 40];
Therefore in order to obtain their information in an orderly manner, you would first need to found how many elements there are. We can use the total of the first array, by using count()
, then using a for
loop to iterate and obtain each array's information.//get the number of articles
$num = count($article_ids);
//iterate through each article count
for ($i = 0; $i < $num; $i++){
echo 'Article id: '.$article_ids[$i].'<br>';
echo 'Article description: '.$article_descriptions[$i].'<br>';
echo 'Article amount: '.$article_amounts[$i] .'<br>';
}
Create multiple arrays in foreach loop php
Correct me if I got it wrong.
Do you want to do something like this:
function cart_items_array() {
$cartinfo = array();
$carts2 = MultiCart\get_carts();
// All the products
$allTheCarts = array();
foreach ( $carts2 as $cart2_id => $cart2 ) {
// get array of items contained in a cart ...
$items2 = MultiCart\get_cart( $cart_id2 );
foreach ( $items2 as $item2_id => $item2 ) {
$compProduct = array();
$product_name = get_post($item2['product_id'])->post_title;
$familyterms = wp_get_post_terms( $item2['product_id'], 'pa_product-family');
$cat_terms = wp_get_post_terms( $item2['product_id'], 'pa_product-category');
$product_sku = get_post_meta( $item2['product_id'], '_sku', true );
$cartinfo[] = $product_sku;
foreach ($cat_terms as $cat_term) { $cartinfo[] = $cat_term->name; };
foreach ($familyterms as $family) { $cartinfo[] = $family->name; };
$cartinfo[] = $product_name;
$cartinfo[] = $item2['quantity'];
$cartinfo[] = $cart2['name'];
// Store the complete product info
$allTheCarts[] = $cartinfo;
}
}
return $allTheCarts;
}
Printing multiple array items in one loop PHP
use a foreach loop and a counter
$i=0;
foreach($PriceArray as $val){
$StatusArrayVal = $StatusArray[$i];
/*
echo each row
your code
*/
$i++;
}
you will have one value in the $val variable and other in $StatusArrayValyou can echo all the html code or set between tags <? ? >
Calculations multiple arrays in foreach loop?
As CBroe stated in the comments, you can just use the key/index in the foreach loop to create the sum
<?php
$data = [
[
'indexname0' => 'group-id',
'indexname1' => 'name of 1st-item',
'indexname2' => 'state of 1st-item',
'indexname3' => 93.42,
'indexname4' => 'unit of 1st-item',
],
[
'indexname0' => 'group-id',
'indexname1' => 'name of 1st-item',
'indexname2' => 'state of 1st-item',
'indexname3' => 93.12,
'indexname4' => 'unit of 1st-item',
],
[
'indexname0' => 'group-id',
'indexname1' => 'name of 1st-item',
'indexname2' => 'state of 1st-item',
'indexname3' => 89.92,
'indexname4' => 'unit of 1st-item',
],
[
'indexname0' => 'group-id',
'indexname1' => 'name of 1st-item',
'indexname2' => 'state of 1st-item',
'indexname3' => 89.70,
'indexname4' => 'unit of 1st-item',
],
];
foreach($data as $index => $value) {
if (!isset($data[$index+1])) continue;
echo $data[$index+1]['indexname3'] - $data[$index]['indexname3'].'<br />';
}
demo Looping through 3 arrays at the same time php
So we will loop N times and pick out a rand value from each array you have
<?php
$length = 32; //length of random password
$a1 = str_split('0123456789'); // convert to array
$a2 = str_split('%^*+~?!'); //convert to array
$a3 = str_split('abcdefghigklmnopqrstuvwxyz'); // convert to array
$result = ""; //final random password
for($i = 0; $i < $length; $i++){
//choose random array from the three a1, a2, a3
//then choose random value from the chosen array
// note: array_rand is a built-in PHP function
// that accepts an array as the first parameter
// and number of random elements to pick out
// as a second optional parameter that defaults to 1
$values = [$a1,$a2,$a3];
$chosen = array_rand($values);
$result .= $values[$chosen][array_rand($values[$chosen])];
}
//print the result out
echo $result;
?>
I hope this will help!
Related Topics
Moving Array Element to Top in PHP
Why Do PHP Array Examples Leave a Trailing Comma
How to Get Content of Remote HTML Page
Xpath Get Attribute Value in PHP
How to Run a Whois Lookup with PHP or Python
PHP MySQL Charset Utf8 Problems
PHP Code Inside a Laravel 5 Blade Template
Download the Contents of a Url in PHP Even If It Returns a 404
Post Ajax Data to PHP and Return Data
PHP - Regex - How to Extract a Number with Decimal (Dot and Comma) from a String (E.G. 1,120.01)
Sending JavaScript Object to PHP via Ajax
File_Get_Contents(): Stream Does Not Support Seeking/When Was PHP Behavior About This Changed
How to Access My Wamp Server on Another Local Computer
How to Resize and Convert an Uploaded Image to a Png Using Gd
How to Pass an Array of Checked/Unchecked Checkbox Values to PHP Email Generator