Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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 /.. 

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?

$myarray = array($size_of_the_earray); 
like image 534
Reed Richards Avatar asked Mar 22 '11 00:03

Reed Richards


People also ask

How do I create an empty array in PHP?

Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”. At this time, $emptyArray contains “first”, with this command and sending “first” to the array which is declared empty at starting.

Can array size be empty?

The number of bytes in an int array of length n is n * sizeof(int) . So for an empty array, the number of bytes is 0 * sizeof(int) , which is zero. Note that zero-sized arrays are a C extension.

How do you initialize an empty array?

To create an empty array, you can use an array initializer. The length of the array is equal to the number of items enclosed within the braces of the array initializer. Java allows an empty array initializer, in which case the array is said to be empty.

Can you create an array with unknown size?

You can dynamically create a array. But You can not change the size of array once it is declared. You need to create new array of bigger size and then copy the content of old array into it.


1 Answers

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.

$my_array = array_fill(0, $size_of_the_array, $some_data); 

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.

like image 191
Jon Avatar answered Sep 19 '22 12:09

Jon