How to shorten the process of creating an array without the need to write all indexes?

7

For example, if I need to create an array with 20 spaces, do I always have to do this?

$teste = array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,19);

Or is there any way to shorten this process, from 0 to 19?

Something like: $teste = array(0..19);

    
asked by anonymous 30.06.2017 / 19:38

2 answers

13

You can create an array with certain positions using the range() function.

The first argument is number that the first element should begin, and the second argument the maximum value. If the maximum value is less than the value starts the array will be generated in a decreasing way.

There is still a third argument to be passed that determines what should be the interval between the values the default is one.

$teste = range(0, 5);

Output:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)

Example - ideone

Related:

Incrementing letters in PHP?

    
30.06.2017 / 19:40
8

You can use the function array_fill , this function returns a filled array.

$meuArray = array_fill(0, 20, NULL);

Where in this array all spaces will be filled by null.

    
30.06.2017 / 19:42