Loop through arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Loop through arrays

Post by GeXus »

Ok, this seems pretty simple, but I'm sure exactly what the proper way is to loop through arrays like this...

Code: Select all

 
Array
(
    [0] => Array
        (
            [uid] => 123456
            [name] => Mike
            [pic] => http://www.pic.com/img.jpg
        )
 
    [1] => Array
        (
            [uid] => 151342
            [name] => Chad
            [pic] => http://www.pic.com/img2.jpg
        )
 
)
 

Thanks!
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Loop through arrays

Post by Christopher »

Code: Select all

foreach ($myarray as $innerarray) {
    foreach ($innerarray as $key => $value) {
    }
}
 
(#10850)
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Re: Loop through arrays

Post by Zoxive »

Code: Select all

 
$Array = Array(
   0 => Array(
    'uid' => 123456,
    'name' => 'Mike',
    'pic' => 'http://www.pic.com/img.jpg',
    ),
    1 => Array(
      'uid' => 151342,
      'name' => 'Chad',
      'pic' => 'http://www.pic.com/img2.jpg',
    )
);
foreach($Array as $Each){
  print '<pre>'; print_r ($Each); print '</pre>';
}

Code: Select all

<pre>Array
(
    [uid] => 123456
    [name] => Mike
    [pic] => http://www.pic.com/img.jpg
)
</pre><pre>Array
(
    [uid] => 151342
    [name] => Chad
    [pic] => http://www.pic.com/img2.jpg
)
</pre>
For arrays like this that you know the Keys for. Otherwise use another loop like arborint suggested.

Code: Select all

foreach($Array as $Each){
  echo '<img src="' . $Each['pic'] . '"> #' . $Each['uid'] . ' <br/> By: ' . $Each['name'] . '<br/>';
}
Post Reply