Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple foreach without nesting

This first block of code works as expected. It's a foreach to print values from an $fnames key-value array.

foreach($fnames as $fname){
   echo $fname;
}

The $fnames array has an $lnames array that correspond to it, and I'd like to print the lname with the fname at the same time, something like this: but it doesn't compile

foreach($fnames as $fname && $lnames as $lname){
   echo $fname . " " . $lname;
}

I also tried this, but that too doesn't compile.

foreach($fnames,$lnames as $fname,$lname){
   echo $fname . " " . $lname;
}

The only thing that compiled was this, but it didn't give correct results.

foreach($fnames as $fname){
   foreach($lnames as $lnames){
       echo $fname . " " . $lname;
   }
}

How do I get this sort of pairing between the 2 arrays at the same index?

like image 861
stacker Avatar asked Dec 06 '22 02:12

stacker


2 Answers

foreach($fnames as $key => $fname){ 
   echo $fname.' '.$lnames[$key]; 
}
like image 154
Mark Baker Avatar answered Dec 25 '22 23:12

Mark Baker


Another option would be:

foreach(array_map(null,$fnames,$lnames) as $name){
    echo $name[0].' '.$name[1];
}
like image 35
Wrikken Avatar answered Dec 25 '22 23:12

Wrikken