Negative php indices - array_fill

When using php array_fill and negative indices, why php fills only the first negative index and then goes to 0.

For instance:

array_fill(-4,4,10) should fill in -4, -3, -2, -1 and 0 , but it is -4, 0, 1, 2, 3

The manual indicates this behavior, but not why.

Can anyone tell why this is?

+6
source share
2 answers

Looking at the source for PHP, I can see exactly why they did it!

What they do is create the first record in the array. In PHP, it looks like this:

 $a = array(-4 => 10); 

Then they add each new entry as follows:

 $count--; while ($count--) { $a[] = 10; } 

If you do this in exactly the same way, you will see the same behavior. A super short PHP script demonstrates this:

 <?php $a = array(-4 => "Apple"); $a[] = "Banana"; print_r($a); ?> 

Result: Array ( [-4] => Apple [0] => Banana )

Note Yes, I used PHP instead of the C source that they used, since the PHP programmer can understand this much better than the original source. This is about the same effect, however, since they use PHP functions to generate results ...

+4
source

Perhaps because the document states: http://www.php.net/manual/en/function.array-fill.php

If start_index is negative, the first index of the returned array will be start_index, and the following indices start from zero (see example).

+2
source

All Articles