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

Asked

Viewed 91 times

7

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

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

Or have some way to shorten that process, that 0 to 19?

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

2 answers

13


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

The first argument is the number that must begin the first element and the second the maximum value. If the maximum value is less than the value starts the array will be generated decreasingly.

There is still a third argument when being passed it determines what should be the interval between the values the default is a.

$teste = range(0, 5);

Exit:

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

Example - ideone

Related:

Increment letters in PHP?

  • Does Ai work the same way? $test[1] = "Test"; Up to 5?

  • @Lucascarvalho will fill the values of the array with the specified 'start' and 'end'. vc wants the value to be fixed?

  • Got rray, it will do yes what I want :) Thank you very much!

  • @Other options for starting an array are functions: array_pad, array_fill and array_fill_keys. For each case one or the other suits the situation better.

  • I’ll study them, look for more! I didn’t know about them. Thank you!

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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.