PHP: initialize array using array_fill()

Using the function array_fill() you can easily initialize your array with a defined value. For example you need an array $array which will have 10 fields and each field will contain 'x'. Using the array_fill() the task will be simple.

$array = array_fill(0, 10, 'x');
print_r($array);


Here the second parameter of the function is the number of fields of the array after the provided index. It must be a positive integer. If you put number of fields is 0, means the second parameter. You'll get the below error.

Warning: array_fill(): Number of elements must be positive in E:\temp\temp.php on line 3

For the above code, the output will be,
Array
(
[0] => x
[1] => x
[2] => x
[3] => x
[4] => x
[5] => x
[6] => x
[7] => x
[8] => x
[9] => x
)

Comments

Anonymous said…
Thankyou. It helped.