RE: [PHP] foreach() over a list of arrays?

From: Date: Sun, 11 May 2003 09:10:52 +0000
Subject: RE: [PHP] foreach() over a list of arrays?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-147192@lists.php.net to get a copy of this message
> -----Original Message----- > Eric Pretorious from Sunnyvale, CA wrote: [snip] > I'm a veteran Perl programmer who's used to things like... > > @array1 = qw(one two three); > @array2 = qw(four five); > > foreach $element (@array1, @array2) { > # Do something... > } > > Is there any way to do this in PHP? e.g., > > $coach = 'fred'; > $manager = 'fred'; > $asst_coaches = array('wilma','barney'); > > foreach ($coach,$manager,$asst_coaches as $staff_member) { > print $staff_member; > } The string is not gonna mix in with the array. Despite PHPs loose type support Coach and Manager will need to be put into arrays to be combined. $coach = array('fred'); $manager = array('fred'); Then you can use array_merge....the PHP doc example for array_merge is: $array1 = array ("color" => "red", 2, 4); $array2 = array ("a", "b", "color" => "green", "shape" => "trapezoid", 4); $result = array_merge ($array1, $array2); // to show the result... print_r( $result ); You'll see this... Array ( [color] => green [0] => 2 [1] => 4 [2] => a [3] => b [shape] => trapezoid [4] => 4 ) NB. This should work fine unless you have associative arrays. As you can see the $result color element is only 'green' but it was in both initial arrays. $coach = array('fred'); $manager = array('fred'); $asst_coaches = array('wilma','barney'); $staff_array = array_merge( $coach, $manager, $asst_coaches ); foreach ($staff_array as $staff_member) { print $staff_member; } Rgds, Ben

« previous php.general (#147192) next »