magnolia
magnolia

Reputation: 43

Multidimensional arrays

I have a php multidimensional array which looks like this:

$fields = array( array('input', 'title', 'slug', 'keywords'), 
     array('textarea', 'content'), 
     array('radio', 'active', 'active2', 'active3', 'active4', 'active5')
);

and I am accessing the array, like this.

However because some arrays contain more values than others I am having trouble, as you can see below $type < 2...how do I fix this?

for($type = 0; $type < 2; $type++) {
    for($field = 0; $field < 2; $field++) {
        echo $fields[$type][$field];
    }
}

Upvotes: 2

Views: 263

Answers (3)

hakre
hakre

Reputation: 197564

count() is giving you the number of items in an array:

for($type = 0; $type < count($fields); $type++) {
    for($field = 0; $field < count($fields[$type]); $field++) {
        echo $fields[$type][$field];
    }
}

Often foreach is easier to use and will create code that you can change easier.

Upvotes: 0

Brice Favre
Brice Favre

Reputation: 1527

You can use array_walk_recursive:

<?php
    array_walk_recursive($fields, 'echo');
?>

Upvotes: 1

marchaos
marchaos

Reputation: 3444

Use a foreach:

foreach ($fields as $values)
{
   foreach ($values as $value) 
   {
       echo $value;
   }
}

Upvotes: 7

Related Questions