Skip to content
Advertisement

How to create an empty array in PHP with predefined size?

I am creating a new array in a for loop.

JavaScript

PHP keeps complaining about the offset since for each iteration I add a new index for the array, which is kind of stupid.

JavaScript

Is there some way to predefine the number items in the array so that PHP will not show this notice?

In other words, can I predefine the size of the array in a similar way to this?

JavaScript

Advertisement

Answer

There is no way to create an array of a predefined size without also supplying values for the elements of that array.


The best way to initialize an array like that is array_fill. By far preferable over the various loop-and-insert solutions.

JavaScript

Every position in the $my_array will contain $some_data.

The first zero in array_fill just indicates the index from where the array needs to be filled with the value.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement