87

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);
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Reed Richards
  • 4,178
  • 8
  • 41
  • 55
  • 3
    PHP shouldn't be complaining when you're assigning to those indices. – BoltClock Mar 22 '11 at 00:44
  • 6
    Could you provide actual code that produces the error? The code supplied is invalid. You should not get an undefined offset error from an array when setting an index value. – Hamish Mar 22 '11 at 00:46

7 Answers7

155

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.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Notice: Undefined offset: 1 in include() (line 23 of / Notice: Undefined offset: 2 in include() (line 23 of / ... – Reed Richards Mar 22 '11 at 00:43
  • 2
    @Reed: This sounds like you are trying to read from the array, while your example code looks like you 're trying to *write*. Which one is it? – Jon Mar 22 '11 at 00:44
  • You were right. In the same line of the code I was reading from another array which thought was ok. Lesson learned don't code after bed time...thanks! – Reed Richards Mar 22 '11 at 00:48
  • 2
    @Reed, this is why we request the actual code being run. It makes it easier for us to provide useful, accurate answers. – Charles Mar 22 '11 at 01:15
  • The first sentence of this answer is not at all helpful. Seeding an array with values is a common use case in programming. – peterjwest May 03 '16 at 14:57
  • @peterjwest of course, but the fact is you cannot "create an empty array with predefined size" in PHP. I'm not sure what kind of answer you expect in this situation. – Jon May 03 '16 at 16:30
  • 1
    Okay I do see what you mean, the wording of the question isn't ideal. A better start to the answer might be "It isn't possible have an array in PHP that has a length different to the number of values in the array. Each value must be defined before being accessed, or guarded with a an `isset` check" – peterjwest May 04 '16 at 12:18
  • I've tried to come up with a better wording than "There is not a way to do that." please check if it is correct. I've also removed some fluff as "For posterity". I can only hope that that sentence is still fluff, anyway, please review changes if it is fluff. – Maarten Bodewes Jan 04 '19 at 09:34
  • If you initialize all values as null then technically it is an empty array like in C or Java. array_fill (0 , $num , null) – PHP Guru Mar 20 '20 at 15:40
24

Potentially relevant- if you want to initialize and fill an array with a range of values, use PHP's (wait for it...) range function:

$a = range(1, 5);  // array(1,2,3,4,5)
$a = range(0, 10, 2); // array(0,2,4,6,8,10)
Madbreaks
  • 19,094
  • 7
  • 58
  • 72
19

You can't predefine a size of an array in php. A good way to acheive your goal is the following:

// Create a new array.
$array = array(); 

// Add an item while $i < yourWantedItemQuantity
for ($i = 0; $i < $number_of_items; $i++)
{
    array_push($array, $some_data);
    //or $array[] = $some_data; for single items.
}

Note that it is way faster to use array_fill() to fill an Array :

$array = array_fill(0,$number_of_items, $some_data);

If you want to verify if a value has been set at an index, you should use the following: array_key_exists("key", $array) or isset($array["key"])

See array_key_exists , isset and array_fill

Jean-Philippe Leclerc
  • 6,713
  • 5
  • 43
  • 66
  • 2
    Note that the shorthand `$array[] = $some_data` is faster than `array_push()` for single items – Phil Mar 22 '11 at 00:49
5

PHP Arrays don't need to be declared with a size.

An array in PHP is actually an ordered map

You also shouldn't get a warning/notice using code like the example you have shown. The common Notice people get is "Undefined offset" when reading from an array.

A way to counter this is to check with isset or array_key_exists, or to use a function such as:

function isset_or($array, $key, $default = NULL) {
    return isset($array[$key]) ? $array[$key] : $default;
}

So that you can avoid the repeated code.

Note: isset returns false if the element in the array is NULL, but has a performance gain over array_key_exists.

If you want to specify an array with a size for performance reasons, look at:

SplFixedArray in the Standard PHP Library.

Jacob
  • 8,278
  • 1
  • 23
  • 29
  • I am trying to understand why is the default PHP array not optimized for performance. The manual says, it is actually an ordered map. How different is that from a hash map or hash table? The concept of a hash table is clear to me, the way it is optimized for scalability as well as random access, however, a hash map is still not clear. – Sandeepan Nath Jun 05 '16 at 10:13
  • It is performant, but it won't always be as performant as an array that has a specified size. – Jacob Jun 06 '16 at 18:49
  • As of PHP 7, numeric ascending arrays are no longer stored as ordered maps. They're stored internally as C arrays. – PHP Guru Mar 21 '20 at 07:26
5
 $array = new SplFixedArray(5);
   echo $array->getSize()."\n";

You can use PHP documentation more info check this link https://www.php.net/manual/en/splfixedarray.setsize.php

Yaser Darzi
  • 1,480
  • 12
  • 24
user10620381
  • 61
  • 1
  • 4
4

There is also array_pad. You can use it like this:

$data = array_pad($data,$number_of_items,0);

For initializing with zeros the $number_of_items positions of the array $data.

localheinz
  • 9,179
  • 2
  • 33
  • 44
Academia
  • 3,984
  • 6
  • 32
  • 49
0

PHP provides two types of array.

  • normal array
  • SplFixedArray

normal array : This array is dynamic.

SplFixedArray : this is a standard php library which provides the ability to create array of fix size.