PHP: Best way to iterate two parallel arrays?
You can use a MultipleIterator
:
$iterator = new MultipleIterator;
$iterator->attachIterator(new ArrayIterator($array1));
$iterator->attachIterator(new ArrayIterator($array2));
foreach ($iterator as $values) {
var_dump($values[0], $values[1]);
}
You can find more examples concerning the various options in the docs. 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>';
}
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',
...
);
Can I iterate through two loops of equal size with foreach?
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 bothA "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
}
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];
}
Foreach loop two unequal array
You can use...how to loop through these 2 arrays and still manage to get all values when both arrays have different number of elements.
for
loop for this. The solution is:
- Take length of the longest array as the condition for
for
loop. - Use
array_key_exists()
function to check whether the index exists in the particular array or not, and display the element accordingly.
$code = array("R9","R10","R11","R12");
$names = array("Robert","John","Steve","Joe","Eddie","Gotham");
$maxLength = count($code) > count($names) ? count($code) : count($names);
for($i = 0; $i < $maxLength; ++$i){
echo array_key_exists($i, $code) ? 'The Code is '. $code[$i] : "";
echo array_key_exists($i, $names) ? ' The Name is '. $names[$i] : "";
echo "<br />";
}
Output:The Code is R9 The Name is Robert
The Code is R10 The Name is John
The Code is R11 The Name is Steve
The Code is R12 The Name is Joe
The Name is Eddie
The Name is Gotham
foreach loop with two arrays
Use PHP's array_values
function to get both array with same indexing, then do the foreach:
$data = [
"arra1" => array("1" => "orange", "2" => "banana", "3" => "apple"),
"data-array" => array("first" , "second" , "third")
];
$labels = array_values($data["arra1"]);
$values = array_values($data["data-array"]);
foreach($labels as $index => $value) {
$optionValue = $index+1;
echo "<option value={$optionValue} data-value='{$values[$index]}'>{$labels[$index]}</option>";
}
Related Topics
Force Cache Refresh After Deployment
Shortcodes Inside a Shortcode - Wordpress
Calling a PHP Function from an HTML Form in the Same File
PHP Local Server Invalid Request (Unexpected Eof)
Programming Multi-Language PHP Applications
MySQL and Query to Satisfy on Same Column
When Should I Close a Database Connection in PHP
How to Add Item to the JSON File Formatted Array
Png Transparency Resize with Simpleimage.PHP Class
PHP Dom Textcontent VS Nodevalue
Pdo_Sqlite Driver Not Present.. What to Do