Multiple array in foreach loop in php

I want to generate a selectbox using two arrays, one containing the country codes and another containing the country names.

This is an example:

<?php
    $codes = array('tn','us','fr');
    $names = array('Tunisia','United States','France');

    foreach( $codes as $code and $names as $name ) {
        echo '<option value="' . $code . '">' . $name . '</option>';
    }
?>

This method didn't work for me. Any suggestions?

Multiple array in foreach loop in php

Machavity

30.1k26 gold badges87 silver badges98 bronze badges

asked Dec 18, 2010 at 23:41

1

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',
   ...
);

answered Dec 18, 2010 at 23:43

Multiple array in foreach loop in php

alexalex

467k197 gold badges865 silver badges975 bronze badges

2

foreach operates on only one array at a time.

The way your array is structured, you can array_combine() them into an array of key-value pairs then foreach that single array:

foreach (array_combine($codes, $names) as $code => $name) {
    echo '<option value="' . $code . '">' . $name . '</option>';
}

Or as seen in the other answers, you can hardcode an associative array instead.

answered Dec 18, 2010 at 23:44

BoltClockBoltClock

675k155 gold badges1362 silver badges1334 bronze badges

3

Use array_combine() to fuse the arrays together and iterate over the result.

$countries = array_combine($codes, $names);

answered Dec 18, 2010 at 23:43

0

array_map seems good for this too

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

array_map(function ($code, $name) {
    echo '<option value="' . $code . '">' . $name . '</option>';
}, $codes, $names);

Other benefits are:

  • If one array is shorter than the other, the callback receive null values to fill in the gap.

  • You can use more than 2 arrays to iterate through.

answered Jul 29, 2019 at 14:41

belugabeluga

1,0711 gold badge7 silver badges11 bronze badges

3

Use an associative array:

$code_names = array(
                    'tn' => 'Tunisia',
                    'us' => 'United States',
                    'fr' => 'France');

foreach($code_names as $code => $name) {
   //...
}

I believe that using an associative array is the most sensible approach as opposed to using array_combine() because once you have an associative array, you can simply use array_keys() or array_values() to get exactly the same array you had before.

answered Dec 18, 2010 at 23:44

Jacob RelkinJacob Relkin

158k32 gold badges341 silver badges318 bronze badges

1

This worked for me:

$codes = array('tn', 'us', 'fr');
$names = array('Tunisia', 'United States', 'France');
foreach($codes as $key => $value) {
    echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "<br>";
}

Multiple array in foreach loop in php

nyedidikeke

6,2127 gold badges43 silver badges53 bronze badges

answered Feb 19, 2017 at 19:35

delAmuxdelAmux

741 silver badge6 bronze badges

0

Your code like this is incorrect as foreach only for single array:

<?php
        $codes = array('tn','us','fr');
        $names = array('Tunisia','United States','France');

        foreach( $codes as $code and $names as $name ) {
            echo '<option value="' . $code . '">' . $name . '</option>';
            }
?>

Alternative, Change to this:

<?php
        $codes = array('tn','us','fr');
        $names = array('Tunisia','United States','France');
        $count = 0;

        foreach($codes as $code) {
             echo '<option value="' . $code . '">' . $names[count] . '</option>';
             $count++;
        }

?>

answered May 21, 2018 at 5:12

Multiple array in foreach loop in php

SnowbasesSnowbases

2,2082 gold badges19 silver badges25 bronze badges

0

Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

becomes:

$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');

answered Dec 18, 2010 at 23:45

JakubJakub

20.3k8 gold badges64 silver badges92 bronze badges

1

You can use array_merge to combine two arrays and then iterate over them.

$array1 = array("foo" => "bar");
$array2 = array("hello" => "world");
$both_arrays = array_merge((array)$array1, (array)$array2);
print_r($both_arrays);

answered May 17, 2012 at 15:38

Multiple array in foreach loop in php

Haider AliHaider Ali

8582 gold badges8 silver badges26 bronze badges

All fully tested

3 ways to create a dynamic dropdown from an array.

This will create a dropdown menu from an array and automatically assign its respective value.

Method #1 (Normal Array)

<?php

$names = array('tn'=>'Tunisia','us'=>'United States','fr'=>'France');

echo '<select name="countries">';

foreach($names AS $let=>$word){
    echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';
 
?>


Method #2 (Normal Array)

<select name="countries">

<?php

$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>

</select>


Method #3 (Associative Array)

<?php

$my_array = array(
     'tn' => 'Tunisia',
     'us' => 'United States',
     'fr' => 'France'
);

echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
    echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>

answered Aug 7, 2013 at 7:50

Multiple array in foreach loop in php

Funk Forty NinerFunk Forty Niner

74.3k15 gold badges66 silver badges134 bronze badges

2

Walk it out...

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
  • PHP 5.3+

    array_walk($codes, function ($code,$key) use ($names) { 
        echo '<option value="' . $code . '">' . $names[$key] . '</option>';
    });
    
  • Before PHP 5.3

    array_walk($codes, function ($code,$key,$names){ 
        echo '<option value="' . $code . '">' . $names[$key] . '</option>';
    },$names);
    
  • or combine

    array_walk(array_combine($codes,$names), function ($name,$code){ 
        echo '<option value="' . $code . '">' . $name . '</option>';
    })
    
  • in select

    array_walk(array_combine($codes,$names), function ($name,$code){ 
        @$opts = '<option value="' . $code . '">' . $name . '</option>';
    })
    echo "<select>$opts</select>";
    

demo

answered Mar 25, 2014 at 5:59

<?php

$codes = array ('tn','us','fr');
$names = array ('Tunisia','United States','France');

echo '<table>';

foreach(array_keys($codes) as $i) {

     echo '<tr><td>';
     echo ($i + 1);
     echo '</td><td>';
     echo $codes[$i];
     echo '</td><td>';
     echo $names[$i];
     echo '</td></tr>';
}

echo '</table>';

?>

answered Sep 7, 2015 at 2:19

r5dr5d

5855 silver badges24 bronze badges

foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a while loop:

while(($code = each($codes)) && ($name = each($names))) {
    echo '<option value="' . $code['value'] . '">' . $name['value'] . '</option>';
}

each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.

answered Jan 6, 2017 at 18:53

PerceptorIIPerceptorII

1191 gold badge1 silver badge5 bronze badges

1

Instead of foreach loop, try this (only when your arrays have same length).

$number = COUNT($_POST["codes "]);//count how many arrays available
if($number > 0)  
{  
  for($i=0; $i<$number; $i++)//loop thru each arrays
  {
    $codes =$_POST['codes'][$i];
    $names =$_POST['names'][$i];
    //ur code in here
  }
}

answered Mar 12, 2017 at 14:45

fchanfchan

211 bronze badge

array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an attempt to update products quantities in a shopping cart.

Multiple array in foreach loop in php

Dave Clemmer

3,78712 gold badges48 silver badges72 bronze badges

answered Dec 20, 2012 at 23:45

I think that you can do something like:

$codes = array('tn','us','fr');

$names = array('Tunisia','United States','France');

foreach ($codes as $key => $code) {
    echo '<option value="' . $code . '">' . $names[$key] . '</option>';
}

It should also work for associative arrays.

answered Jul 7, 2016 at 14:49

Multiple array in foreach loop in php

I think the simplest way is just to use the for loop this way:

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

for($i = 0; $i < sizeof($codes); $i++){
    echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}

answered Jul 16, 2016 at 8:13

SeReGaSeReGa

9981 gold badge8 silver badges28 bronze badges

if(isset($_POST['doors'])=== true){
$doors = $_POST['doors'];
}else{$doors = 0;}

if(isset($_POST['windows'])=== true){
$windows = $_POST['windows'];
}else{$windows = 0;}

foreach($doors as $a => $b){

Now you can use $a for each array....

$doors[$a]
$windows[$a]
....
}

answered Feb 7, 2013 at 3:10

Multiple array in foreach loop in php

GviceGvice

3932 silver badges10 bronze badges

I solved a problem like yours by this way:

foreach(array_keys($idarr) as $i) {
 echo "Student ID: ".$idarr[$i]."<br />";
 echo "Present: ".$presentarr[$i]."<br />";
 echo "Reason: ".$reasonarr[$i]."<br />";
 echo "Mark: ".$markarr[$i]."<br />";
}

answered Feb 19, 2013 at 13:34

UlugovUlugov

3474 silver badges9 bronze badges

You should try this for the putting 2 array in singlr foreach loop Suppose i have 2 Array 1.$item_nm 2.$item_qty

 `<?php $i=1; ?>
<table><tr><td>Sr.No</td> <td>item_nm</td>  <td>item_qty</td>    </tr>

  @foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)
<tr> 
        <td> $i++  </td>
        <td>  $item_nm  </td>
        <td> $item_qty  </td>
   </tr></table>

@endforeach `

answered Mar 2, 2015 at 10:43

Multiple array in foreach loop in php

Few arrays can also be iterated like this:

foreach($array1 as $key=>$val){ // Loop though one array
    $val2 = $array2[$key]; // Get the values from the other arrays
    $val3 = $array3[$key];
    $result[] = array( //Save result in third array
      'id' => $val,
      'quant' => $val2,
      'name' => $val3,
    );
  }

answered Oct 20, 2015 at 8:27

Multiple array in foreach loop in php

This will only work if the both array have same count.I try in laravel, for inserting both array in mysql db

$answer = {"0":"0","1":"1","2":"0","3":"0","4":"1"};
$reason_id = {"0":"17","1":"19","2":"15","3":"19","4":"18"};

        $k= (array)json_decode($answer);
        $x =(array)json_decode($reason_id);
        $number = COUNT(json_decode($reason_id, true));
        if($number > 0)  
        {  
        for($i=0; $i<$number; $i++)
        {
            $val = new ModelName();
            $val->reason_id  = $x[$i];
            $val->answer  =$k[$i];
            $val->save();
        }
        }

answered Oct 30, 2021 at 8:22

Multiple array in foreach loop in php

1

it works for me

$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}

answered Jul 17, 2013 at 16:44

How to pass two array in foreach loop PHP?

php $FirstArray = array('aB', 'PQ', 'cd', 'pm'); $SecondArray = array('12', '34', '90', '49'); foreach($FirstArray as $index => $value) { echo $FirstArray[$index]. $SecondArray[$index]; echo "<br/>"; } ?>

How to iterate multidimensional array in PHP?

Looping through multidimensional arrays Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.

How do you use each loop in a multidimensional array?

In the foreach loop, the $element variable will contain the value of the current array item for every iteration. The loop continues till the last element in the array. In the case of the two-dimensional array, we can use the foreach loop to access the first nested array in the first iteration and so on.

How can I run two loops simultaneously in PHP?

To solve this you have to loop through both arrays at once..
array_map() method. (PHP >=5.3).
MultipleIterator method. (PHP >=5.3).
for loop method. (PHP >=4.3).
array_combine() method. (PHP >=5.0).
call_user_func_array() method. (PHP >=5.6).