1

What is the most efficient way in initializing large amount of multidimensional array in PHP?

example: I'm going to create 100 Multidimensional array that look like this:

Array
(
    [1] => Array
        (
            [multi] => 1
        )

    [2] => Array
        (
            [multi] => 2
        )

    [3] => Array
        (
            [multi] => 3
        )

    [4] => Array
        (
            [multi] => 4
        )

    [5] => Array
        (
            [multi] => 5
        )
      .......
)

Currently, I'm using this code to create the array shown above:

// 100 arrays
for($i=1; $i<=100; $i++){
   $array[$i]['multi']=$i;
}

I also found an alternative way by using array_fill() and array_fill_keys(), but It only allows the same value to be initialized in an array:

$array = array_fill(1, 100, array_fill_keys(array("multi"), "value_here"));

QUESTION: Is there a more efficient way in initializing this kind of array in terms of speed?

6
  • 1
    I'm not sure I follow the point of the "multi" key. if the data you want to store is just sequentially ascending integers, why do you need this structure? Seems like range(1, 100) should do the job just fine. Can you post a less contrived example? Thanks for the clarification. Commented Aug 21, 2019 at 5:36
  • use a generator Commented Aug 21, 2019 at 5:41
  • sorry.The structure of my array has one or more different keys inside them, except for the key "multi". They all have the key "multi". I only include the code for initializing the "multi" key. Commented Aug 21, 2019 at 5:46
  • If it's static then save it as a json and you won't have to initialize it each time Commented Aug 21, 2019 at 5:52
  • 1
    The fastest way to initialize an Array Is by the standard Array initializer: $array = [...]; Commented Aug 21, 2019 at 5:58

1 Answer 1

1

You could use array_map over the range of values you want:

$array = array_map(function ($v) { return array('multi' => $v); }, range(0, 5));
print_r($array);

Output:

Array
(
    [0] => Array
        (
            [multi] => 0
        )
    [1] => Array
        (
            [multi] => 1
        )
    [2] => Array
        (
            [multi] => 2
        )
    [3] => Array
        (
            [multi] => 3
        )
    [4] => Array
        (
            [multi] => 4
        )
    [5] => Array
        (
            [multi] => 5
        )
)

If you don't want the 0 element, just unset($array[0]);

Demo on 3v4l.org

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

Comments

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.