Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling an array with numbers sequentially

I have a number (e.g. 6) that is dynamically generated and I would like to fill an array with the numbers 1 through the dynamically generated number (in this example, 6):

array(1, 2, 3, 4, 5, 6);

The only way I know to do this at the moment is by using a for loop, but I'm wondering if there's a better way, something similar to array_fill. I looked at array_fill, but it doesn't look like it will take a number and increment it for a set number of times.

like image 333
Francis Lewis Avatar asked Feb 10 '12 20:02

Francis Lewis


People also ask

How do you fill an array in a sequence?

Here's how you can fill a range within an array: const fillRange = (start, end) => { return Array(end - start + 1). fill().

How do you order an array of consecutive numbers?

Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.

How do you fill an array with numbers in Python?

fill() method is used to fill the numpy array with a scalar value. If we have to initialize a numpy array with an identical value then we use numpy. ndarray. fill().

How do you make an array of numbers?

An array is created using square brackets ( [ and ] ). For example, an array of numbers can be created as follows: let arr: number[] = []; To create an array of values, you simply add square brackets following the type of the values that will be stored in the array: number[] is the type for a number array.


1 Answers

Use range:

$arr = range(1,6);
// Returns an array of elements from start to limit, inclusive.
like image 116
Josh Avatar answered Oct 25 '22 12:10

Josh