Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through an array php

People also ask

How do you loop through a multidimensional array in PHP?

Looping through multidimensional arrays Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.

Which loop would you prefer to go through an array in PHP briefly describe?

If you have an array variable, and you want to go through each element of that array, the foreach loop is the best choice.

What is foreach in PHP?

The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.


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.


foreach($array as $item=>$values){
     echo $values->filepath;
    }