Reed Richards Reed Richards - 5 months ago 10
PHP Question

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

I am creating a new array in a for loop.

for $i < $number_of_items
$data[$i] = $some_data;


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

Notice: Undefined offset: 1 in include() (line 23 of /...
Notice: Undefined offset: 1 in include() (line 23 of /..
Notice: Undefined offset: 1 in include() (line 23 of /..

How do I solve this? Is there some way to predefine the number items in the array so that php wont throw the stupid error? Like

$myarray = array($size_of_the_earray);

Jon Jon
Answer

There is not a way to do that.

For posterity

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