phparraysloops

How to access data in a 2d array?


I have an array, the output of print_r is:

Array (
    [0] => Array (
        [ID] => 1
        [col1] => 1
    )
    [1] => Array (
        [ID] => 2
        [col1] => 2
    )
)

Could you help of kind of array it is? So that I could research more about it? What I want is to get ID and col1 values

I've tried to use foreach:

foreach ($array_name as $key => $value) {
     print "$key holds $value\n";
 }

The output I get is 0 holds Array 1 holds Array And I would simply like to get:

1 1
2 2

Solution

  • It's a multi dimensional array, or an array where each element is another array. So you'll need to loop twice. Try this to look at it:

    foreach($array_names as $arr)
    {
      foreach($arr as $key => $val)
      {
        print "$key = $val\n";
      }
    }
    

    Or, to get your just added desired output, do this:

    foreach($array_names as $arr)
    {
      foreach($arr as $key => $val)
      {
        print "$val ";
      }
      print "\n";
    }
    

    Or this:

    foreach($array_names as $arr)
    {
       print $arr['ID'] . " " . $arr['col1'] . "\n";
    }
    

    or a few other ways but you should be getting the picture.