Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 4 down vote accepted

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.

share|improve this answer
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? – user2884319 Mar 4 '14 at 23:17
@user2884319 No, there's nothing wrong with it. – Corbin Mar 4 '14 at 23:21

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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