Count through dimension 2 of an array (of arrays)

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
Idiot88
New php-forum User
New php-forum User
Posts: 19
Joined: Thu Jan 25, 2018 2:56 pm

Sat Feb 03, 2018 8:17 am

Hi

I use count() to loop through dimension 1 of an array. But how can I loop throug dimension 2?

Thanks.

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 693
Joined: Mon Feb 22, 2016 5:52 pm

Sat Feb 03, 2018 11:39 am

In answer to your question: Create a sub loop.

It would be better to take advantage of the foreach loop:

Code: Select all

// Create a multidimensional test array
$my_array = [
  1,
  2,
  [
    10,
    11,
    12
  ],
  3
];

// Iterate through the array
foreach ($my_array as $ma) {
  // If the array contents are an array, loop through that, otherwise echo (or whatever) the element
  if (is_array($ma)) {
    foreach ($ma as $a) {
      echo '&nbsp;&nbsp;', $a,'<br>'; // Indent to show deeper level
    }
  } else {
    echo $ma,'<br>';
  }
}
If you want to get more complicated, then there are other options; it's all down to what you need to do.

Post Reply