Loop through an array php Loop through an array php arrays arrays

Loop through an array php


Using foreach loop without key

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

Using foreach loop with key

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

Using for loop

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

var_dump is a really useful function to get a snapshot of an array or object.


Ok, I know there is an accepted answer but… for more special cases you also could use this one:

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

Or in a more un-complex way:

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

This will allow you to manipulate the data in an easier way.


Starting simple, with no HTML:

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

And you can otherwise manipulate the fields in the foreach.