0

I did not find similar question

1

$form['level1']['level2'][] = array(
    'data' => 'some data',
    'type' => 'some type',
);
//etc

2

 $form = array(
   'level1' => array(
      'level2' => array(
         array(
            'data' => 'some data',
            'type' => 'some type',
         ), 
         //etc
       ),
    ),
 );
5
  • 2 is more readable than 1. Apr 16, 2013 at 17:11
  • For the number of picoseconds difference that this will make to your scripts, efficiency is largely an irrelevance.... ask yourself instead "which is more readable?"
    – Mark Baker
    Apr 16, 2013 at 17:11
  • 1
    Version 1 will give you a notice/warning if $form['level1']['level2'] is not already an array.
    – nickb
    Apr 16, 2013 at 17:11
  • I agree, same to efficiency? I am working with Drupal and it has a lot of nested large arrays, I am just curiuos
    – Codium
    Apr 16, 2013 at 17:11
  • imho 1 is more readable than 2, but as stated, you would need to define $form['level1']['level2'] as an array first
    – winkbrace
    Apr 16, 2013 at 17:17

2 Answers 2

2

This is absolutely microoptimizing...

Test 1: 9.0906839370728
Test 2: 8.5538339614868

But the second is more efficient. For example [] is slower as it first has to check for the last index etc... Also the first has to first check if the array already exists (at every dimension) while in the second case it is clear to PHP that there is a new array.

P.s.: But I don't really know, as the first is less to parse than the second. The parser time I didn't measure... (And I don't suppose that the arrays are now very often recreated?)

-1

2 is more readable than 1.

Also, if you going to play without warning, 1 would be:

$arr = array();
$arr["level1"] = array();
$arr["level1"]["level2"] = array();
//... etc
4
  • 2
    Which also makes #1 less efficient - because each level/block has to be separately defined
    – Mark Baker
    Apr 16, 2013 at 17:13
  • What warnings are you referring to specifically?
    – webbiedave
    Apr 16, 2013 at 17:25
  • Notice: Undefined offset Apr 16, 2013 at 17:30
  • Disagree, e.g: $new_array["level1"]["level2"][] = 'value' give you correct nested array without any notices (E_ALL)
    – Codium
    Apr 16, 2013 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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