views:

46

answers:

3

Which of the following two data structures is "better"?

array('key'=>array(1,2,3,4))

OR:

array('key',array(1,2,3,4))

i.e., is it better to store the array as the second element in a two element array, or as the single element in an array with the key, 'key'.

Assume that for my purposes, in matters of convenience, they are equivalent. I am only curious whether one uses more resources than the other.

+4  A: 

You use whichever one is appropriate for what you're trying to store.

If the key relates to the array of values and its unique then use key/value.

Worrying about resources used in this kind of situation are micro-optimizations and an irrelevant distraction.

cletus
+2  A: 

if that's the full size of the array, then that's fine.

However, if you actually have an array like

array(
  array('key', array(...)),
  array('key', array(...)),
  array('key', array(...)),
  etc
);

instead of

array(
  'key' => array(...),
  'key' => array(...),
  'key' => array(...),
);

Then it's not only odd, it's very unreadable.

Tor Valamo
+1  A: 

The beaut thing of having named key to value is this:

"I want the value of Bob"

$bob = $myArray['bob'];

instead of

foreach($myArray as $key => $value) {

    if ($value[0] === 'bob') { // the first value of your 2nd type
        $bob = $myArray[1]; // get the next value.
    }

}

Of course, for the 2nd example you could consider end(). But compare the 2, it is obvious the first example wins!

alex