nobito nobito - 6 months ago 16
PHP Question

putting a foreach inside foreach

I'm trying to loop some array using

foreach
.
This is the code which demonstrates what I'm doing:

$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");

foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-".$key2."-".$val2;
}
}


However, this outputs


32-0-5

32-1-3

32-2-2

32-3-1


and I want to display it like this instead



32-1-5

45-2-3

67-3-2

89-3-1



How can I solve this? Since I'm a beginner I don't know what to do.

Answer

You don't want to loop over the 2nd array, you just want to get the value at a certain position. Try it like this:

foreach($arr1 as $key => $val){
  $val2 = $arr2[$key];
  echo $val."-".($key+1)."-".$val2;
}
Comments