Multiple foreach without nesting

This first block of code works as expected. This is a foreach for printing values ​​from an array of $fnames values.

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

The $fnames array has an $lnames array that matches it, and I would like to print lname with the name fname at the same time, something like this: but it does not compile

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

I tried this too, but this does not compile either.

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

The only thing that was compiled, but it did not give the correct results.

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

How do I get this kind of pairing between two arrays at the same index?

+4
source share
3 answers
 foreach($fnames as $key => $fname){ echo $fname.' '.$lnames[$key]; } 
+9
source

Another variant:

 foreach(array_map(null,$fnames,$lnames) as $name){ echo $name[0].' '.$name[1]; } 
+5
source

If you do not want to combine arrays, you will need two generators at once. Fortuantely, PHP has a way to do this with arrays. However, it is a bit old school.

 reset($fnames); reset($lnames); do { print current($fnames).' '.current($lnames)."\n"; } while( next($fnames) && next($lnames) ); 

Although this is a slightly contrived example, it is still a useful method.

+2
source

All Articles