22 Votes

PHP: Fill Array with Sequence of Numbers or Characters

Tutorial by Stefan Trost | Last update on 2023-01-18 | Created on 2014-03-19

Using the PHP function array_fill() you can easily create an array in which all elements have the same value. But what can we do if we would like to create an array containing a sequence of different values uncomplicated and quickly? For example an array containing the elements 1950 till today as years or other number or character frequencies?

Of course, we could create an empty array and then fill it in a loop with the desired values by increasing the individual values in the loop by the desired step. But it is easier. Because PHP offers us the function range().

Sequences of Numbers

The function range() expects the first element of the resulting arrays as first parameter and the last element as second parameter. The following three examples demonstrate this with different initial and end values:

$arr = range(0, 5);
// is equal to: array(0, 1, 2, 3, 4, 5)

$arr = range(2, 4);
// is equal to: array(2, 3, 4)

$arr = range(5, 3);
// is equal to: array(5, 4, 3);

As you can see, it is possible to write ascending as well as descending values into the array. We get an ascending sequence when the second parameter is larger than the first one. We get a descending sequence when the second parameter is smaller than the first one.

Increment of Values

Since PHP 5 it is possible to manipulate the increment of the values using a third parameter.

$arr = range(0, 40, 10);
// is equal to: array(0, 10, 20, 30, 40);

As an optional third parameter (step) we have passed 10 here. With this, the result is an ascending sequence of numbers in increments of ten starting at our first parameter and ending with our second parameter.

Sequences of Characters

But it is not only possible to create sequences of numbers with the help of range(). In the same way, we can also create sequences of characters. Again, we only need to pass the first as well as the last letters of our desired sequence as the first two parameters:

$arr = range('a', 'c');
// is equal to: array('a', 'b', 'c')

In this example, we are creating an array containing the three elements "a", "b" and "c".

ReplyPositiveNegative

About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.