0

I am just wondering if this code I have is a multidimensional associative array. I only ask because after doing research on multidimensional arrays I could't find the difference between the two because they looked the same. Is this code a associative array or just a standard multidim array?

$win = array('Name'=> 
                        array('Jane Doe ', 'Nash Patel ', 'Joe Public '), 
             'Date'=>
                        array('7 October 2015 ', '14 October 2014 ', '12 October 2016 '));

foreach($win as $element => $namedate) {
    echo '<strong>' . $element . '</strong><br>';
    foreach($namedate as $both) {
       echo $both . '<br/>';
    }
}

1 Answer 1

4

You have a multidimensional array.

The first level is associative because the keys are Name and Date.

The second level subarrays are indexed (not associative). This means Jane Doe's index is 0, Nash Patel is 1, and Joe Public is 2.

Although you can if you wish, keys do not need to be written when declaring indexed elements -- PHP will spare you that tedious job.

Examples:

$one_dim=['Name'=>'Jane Doe ']; // 1-dimensional associative array with one element

$one_dim=['Jane Doe '];         // 1-dimensional indexed array with one element

$mult_dim=[                     // multi-dimensional associative array with indexed subarrays
    'Name'=>[                   // associative
        0=>'Jane Doe ',         // indexed
        1=>'Nash Patel ',       // indexed
        2=>'Joe Public '        // indexed
    ],
    'Date'=>[                   // associative
        0=>'7 October 2015 ',   // indexed
        1=>'14 October 2014 ',  // indexed
        2=>'12 October 2016 '   // indexed
    ]
];
Sign up to request clarification or add additional context in comments.

2 Comments

How am I able to get the whole array to be associative then without making it indexed?
You can manually declare the keys for each subarray. When you declare the keys, php will not apply auto-incremented numeric keys for you. What do you have in mind? Does it help you to use the Name values as keys and Date values as values? Have a look at this demo link.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.