1

StackOverflow has been a great learning center for me, Being an intermediate level programming student, I am now stuck and failing to understand how to manipulate a multidimensional array, I have searched a lot, the tutorials, here... but everything seems very specific to its writer need, so I cannot understand the concept of a multidimensional array

If you dont like my question, at least do not negative vote... just try to understand that I am still in a learning process and using every resource i can (not being able to join a college because of work)

The array I am trying to understand is

$myArray = array(
                    "ChkIns" => array('Morning','Evening'),
                    "Times" => array('11:00:00','16:00:00')
                    //There may be more data here later
                );

I should be able to get the value of ChkIns and Times using a foreach loop but I dont want to use sort of hardcoded code because the above mentioned array may have more indices.

What I am trying to figure out that How to obtain data from an array which have further sub arrays using a foreach loop

2
  • You can use a foreach inside a foreach! Commented Aug 7, 2014 at 14:05
  • I could use foreach($myArray as $key => $val) ?? Commented Aug 7, 2014 at 14:06

1 Answer 1

2

The simple answer is that you can loop over a sub-array as you would any other array. Here's an example, using your $myArray variable:

foreach($myArray as $key => $value) {
    // Here, $value is just another array so you can foreach over it
    foreach($value as $innerKey => $innerValue) {
        // This is now the sub array value, 
        // 'Morning', 'Evening', '11:00:00', etc
    }
}

The $key variable will be set to 'ChkIns' and 'Times', and $innerKey will be an integer since your sub-arrays are numerically indexed.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir... This is a very understanding explanation of using such array :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.