How to fill an array with numbers in PHP?

by madie.koelpin , in category: PHP , 2 years ago

How to fill an array with numbers in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@madie.koelpin You can use range() function to fill an array with numbers sequentially in PHP, here is code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

$arr = range(1, 3);

print_r($arr);
// Output:
//Array
//(
//    [0] => 1
//    [1] => 2
//    [2] => 3
//)
by rachelle_funk , a year ago

@madie.koelpin 

In PHP, there are several ways to fill an array with numbers. One way is to use a for loop and the range function:

1
$numbers = range(1, 10);


This will create an array $numbers that contains the numbers 1 through 10. You can also specify a step value:

1
$even_numbers = range(2, 20, 2);


This will create an array $even_numbers that contains the even numbers from 2 to 20. Another way to fill an array with numbers is using the array_fill function:

1
$numbers = array_fill(0, 10, 1);


This will create an array $numbers that contains 10 elements all with value of 1. You can also use the array_fill_keys function to use a specific key for each element:

1
2
$keys = range(1, 10);
$numbers = array_fill_keys($