Loop through php array

I have this array ... how do you print each file path and file name? What is the best way to do this?

Array ( [0] => Array ( [fid] => 14 [list] => 1 [data] => Array ( [alt] => [title] => ) [uid] => 1 [filename] => trucks_10785.jpg [filepath] => sites/default/files/trucks_10785.jpg [filemime] => image/jpeg [filesize] => 143648 [status] => 1 [timestamp] => 1291424171 [nid] => 8 ) [1] => Array ( [fid] => 19 [list] => 1 [data] => Array ( [alt] => [title] => ) [uid] => 1 [filename] => school.jpg [filepath] => sites/default/files/school.jpg [filemime] => image/jpeg [filesize] => 115355 [status] => 1 [timestamp] => 1292029563 [nid] => 8 ) [2] => Array ( [fid] => 20 [list] => 1 [data] => Array ( [alt] => [title] => ) [uid] => 1 [filename] => Life_is_wonderful_by_iNeedChemicalX.jpg [filepath] => sites/default/files/Life_is_wonderful_by_iNeedChemicalX_0.jpg [filemime] => image/jpeg [filesize] => 82580 [status] => 1 [timestamp] => 1292029572 [nid] => 8 ) [3] => Array ( [fid] => 21 [list] => 1 [data] => Array ( [alt] => [title] => ) [uid] => 1 [filename] => school_rural.jpg [filepath] => sites/default/files/school_rural.jpg [filemime] => image/jpeg [filesize] => 375088 [status] => 1 [timestamp] => 1292029582 [nid] => 8 ) ) 
+86
arrays loops php printing
Dec 11 '10 at 1:11
source share
5 answers

Using a keyless foreach

 foreach($array as $item) { echo $item['filename']; echo $item['filepath']; // to know what in $item echo '<pre>'; var_dump($item); } 

Using a foreach with a key

 foreach($array as $i => $item) { echo $array[$i]['filename']; echo $array[$i]['filepath']; // $array[$i] is same as $item } 

Using a for loop

 for ($i = 0; $i < count($array); $i++) { echo $array[$i]['filename']; echo $array[$i]['filepath']; } 

var_dump is a really useful function for taking a snapshot of an array or object.

+200
Dec 11 '10 at 1:21
source share

Ok, I know there is an accepted answer, but ... for more special cases, you can also use this:

 array_map(function($n) { echo $n['filename']; echo $n['filepath'];},$array); 

Or in a more simple way:

 function printItem($n){ echo $n['filename']; echo $n['filepath']; } array_map('printItem', $array); 

This will allow you to manipulate data in a simpler way.

+6
May 13 '16 at 16:58
source share

Running is simple, without HTML:

 foreach($database as $file) { echo $file['filename'] . ' at ' . $file['filepath']; } 

And you can otherwise manipulate fields in foreach.

+5
Dec 11 '10 at 1:21
source share
 foreach($array as $item=>$values){ echo $values->filepath; } 
+1
Aug 28 '19 at 3:12
source share

You can also use this without creating additional variables or copying data into memory, as foreach () does.

 while (false !== (list($item, $values) = each($array))) { ... } 
0
Sep 19 '19 at 11:00
source share



All Articles