00 Votes

PHP: Create Array and fill/initialize it with Value

Question by Guest | 2014-03-19 at 10:00

I have a PHP script in which I need some arrays.

For example the array $arr which should be preallocated with the value 1 for a length of 10 elements.

Up to now, I have initialized my array in the following way:

$arr = array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1);

However, this is very inconvenient because the arrays can become very long and it is hard to me to write the right number of elements without making any mistakes.

Isn't there any easier way for the initialization of an array in PHP?

2Best Answer2 Votes

The function, you are searching for is called array_fill.

You can pass three parameters to array_fill:

  1. Start-Index
  2. Number of fields that should be written
  3. Value that should be written to the fields

With calling

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

you are doing exactly the same that you wanted to do in your example.

We are passing 0 as a start index (the first index in your array is 0), 10 as the number of fields (your array should have 10 fields) and 1 as the value. This value will be written in all 10 fields.

What is happening if we do not set the start index to 0?

$arr = $array_fill(2, 3, 4);

// $arr[2] = 4; $arr[3] = 4; $arr[4] = 4;

Here, we are beginning with index 2 and we are inserting the value 4 for 3 times. The result is the array below.

After all, PHP ist also providing a function to fill arrays with sequences of numbers or strings - if you do not want to have the same elements in your array.
2014-03-19 at 17:10

ReplyPositive Negative

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.


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