5
\$\begingroup\$

I am initializing a PHP array as follows

$newArray = array();
$newArray['2014-13-03']['SMD']['IMPR'] = 5;
$newArray['2014-13-03']['SMD']['CLICK'] = 10;

I just wanted to check if you think this is a wrong way to insert data into an array. It is working just fine, but I still wanted to check from an optimization standpoint.

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

I would do the definition inline with the declaration:

$newArray = array(
    '2014-13-03' => array(
        'SMD' => array(
            'IMPR' => 10,
            'CLICK' => 10
        )
    )
);

If you wanted to lean towards the more compact side, you could achieve almost the same clarity with something like:

$newArray = array('2014-13-03' => array('SMD' => array(
    'IMPR' => 10,
    'CLICK' => 10
)));

In addition to a bit more clarity (at least in my opinion), this has the advantage of it being more difficult to accidentally mess up the data. Since the parents keys aren't repeated, the keys are either right for both leaves or wrong for both leaves. That should help prevent a rather odd potential bug.


By the way, that's a rather odd data structure unless this is just an example. Three levels deep for such a sparse data set is kind of excessive.


From an optimization standpoint, it's not going to matter how you do it. You're in the realm of microseconds at most. Really it's just the parser that's going to differ on it anyway since I would imagine the parser will change any reasonable incantation of this to the same instructions (I have not confirmed that though).


By the way, $newArray is a terrible variable name in anything but example code. If your real code is using that, change it to a descriptive name.

\$\endgroup\$
2
  • \$\begingroup\$ This is just an example. What I wanted to know is is there anything wrong in setting the multi-dimensional array the way I have done? \$\endgroup\$ Commented Mar 4, 2014 at 23:17
  • \$\begingroup\$ @user2884319 No, there's nothing wrong with it. \$\endgroup\$
    – Corbin
    Commented Mar 4, 2014 at 23:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.