简体   繁体   中英

Which is the more efficient way to store this ordered pair in php?

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

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

OR:

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

ie, 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.

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.

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM