Frank Castle
Frank Castle

Reputation: 345

How to iterate over a multidimensional array starting from a certain key?

I have a multidimensional array that is created from a user form. I would like to iterate over the array in a foreach loop starting from a certain key in the loop. For some reason my below code is not working.

$i = 3; 

foreach ($data as $val) {
    echo $val[$i] . " : " . $val['value'] . "<br />";
    $i++; 
}

output:

Array ( 
    [0] => Array ( [name] => name [value] => name ) 
     [1] => Array ( [name] => code [value] => code ) 
    [2] => Array ( [name] => description [value] => description ) 
     [3] => Array ( [name] => unit-1 [value] => uni 1 ) 
     [4] => Array ( [name] => unit-1-section-1 [value] => unit 1 sect 1 ) 
     [5] => Array ( [name] => unit-2 [value] => unit 2 ) 
     [6] => Array ( [name] => unit-2-section-1 [value] => unit 2 section 2 ) 
    ) 

As you can see, I want to start from the 3rd key in the $data array.

Upvotes: 0

Views: 43

Answers (2)

h2ooooooo
h2ooooooo

Reputation: 39532

Just use a regular for loop and start on the 3 key (I'm guessing that's what you mean by the "3rd key" even though it's actually the 4th):

for ($i = 3; $i < count($data); $i++) {
    echo $data[$i]['name'] . " : " . $data[$i]['value'] . "<br />";
}

Upvotes: 2

sunshinejr
sunshinejr

Reputation: 4854

If you want to start from the 3rd key in EVERY array in $data:

foreach ($data as $val) {
   $count = count($val);
   for($i = 2; $i < $count; $i++)
      echo $val[$i]['name'] . " : " . $val[$i]['value'] . "<br />";
   }
}

Upvotes: 1

Related Questions