00 Votes

PHP: Fill Array with Sequence of Numbers or Characters

Tutorial by Stefan Trost | 2014-03-19 at 16:16

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

Of course, you can also create an empty array and use a loop in which you increase a value storing the steps in the array. But it is easier. Because affords 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.

$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.

Increment of Values

Since PHP 5 it is possible to manipulate the increment of the values.

$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.

Sequences of Characters

But it is not only possible to create sequences of numbers with the help of range(). In the same way, you can also create sequences of characters.

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

In this example, we are creating an array containing the 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.