views:

39

answers:

3

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?

+7  A: 
foreach($fnames as $key => $fname){ 
   echo $fname.' '.$lnames[$key]; 
}
Mark Baker
Should be, given that the keys in the arrays match up.
Brad F Jacobs
+4  A: 

Another option would be:

foreach(array_map(null,$fnames,$lnames) as $name){
    echo $name[0].' '.$name[1];
}
Wrikken
Neat trick, I'll have to remember that technique
Mark Baker
+2  A: 

If you don't want to combine the arrays, you actually need two generators running at once. Fortuantely, PHP has a way of doing this with arrays. It's a little bit old-school, though.

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

Whilst this is a slightly contrived example, it is still a useful technique to know.

staticsan