2

I want to know which one is more optimized?

  1. Defining several separated array

  2. Using nested array keys

Here is an example:

function arr(){
    $arr1 = array();
    $arr2 = array();
    $arr3 = array();

    $arr1['key1'] = 'val1';
    $arr2['key1'] = 'val1';
    $arr3['key1'] = 'val1';

    return array($arr1, $arr2, arr3);
}

OR

function arr(){
    $arr = array();

    $arr['arr1']['key1'] = 'val1';
    $arr['arr2']['key1'] = 'val1';
    $arr['arr3']['key1'] = 'val1';

    return $arr1;
}

Actually I have not any problem, I just want to know, which approach is faster in php? nested key or separated array?!

3
  • 2
    Note that the two functions you've provided will give different results. Commented Oct 7, 2015 at 16:03
  • @AlexShesterov why you think the results will be different? Commented Oct 7, 2015 at 16:05
  • 1
    yes, your array($arr1,...) has different keys. you'll have $arr[0]['key1'], $arr[1]['key2'], etc... Commented Oct 7, 2015 at 16:08

1 Answer 1

2

If you have a fixed set of keys, then create the whole array in a single statement, as below. It will be both the fastest and the most readable way.

function arr(){
    return array(
      array('key1' => 'val1'),
      array('key1' => 'val2'),
      array('key1' => 'val3'),
    );
}

Regarding the performance difference between the two ways — you may benchmark the two functions to find out, as Pamblam did. But the difference will be so minimal that it will barely ever matter.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it was useful. also please remove the last , in the nested array.
@Sajad, note that PHP allows an optional comma after the last array element, see here. It's a matter of taste whether to use it, and it doesn't affect the semantics of the program.
One advantage of using a comma after the last element is: comparing file versions in a version control system. If an additional element is added to the end of the array, the difference will be exactly that one added line if a comma was used. Without a comma, the difference will be the added line and the previous line with the missing comma added.

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.