In this tutorial, you shall learn about PHP array_fill() function which can fill an array with values, with syntax and examples.

PHP array_fill() Function

The PHP array_fill() function fills an indexed array with values. The function basically creates an indexed array of specific size, with specific default value for elements, and with a specified index for the first item.

We can create only indexed arrays using array_fill() function.

Syntax of array_fill()

The syntax of array_fill() function is

array_fill( index, number, value)

where

ParameterDescription
index[mandatory] The first element of the returned array will have this index. The index must be an integer.
number[mandatory] Number of elements to insert in the array. The number must be an integer.
value[mandatory] Value to use for filling the array.

Function Return Value

array_fill() returns the filled array

ADVERTISEMENT

Examples

1. Fill array with a value of “apple”

In this example, we will create an array and fill it with value "apple". The items in array start with index 6, and will have 3 items in total.

PHP Program

<?php
$array1 = array_fill(6, 3, "apple");
print_r($array1);
?>

Output

PHP array_fill() - Fill Array with Values

2. Warning: array_fill() expects parameter 1 to be int

In this example, we will call array_fill() function with a string "a" passed as argument for index parameter.

PHP Program

<?php
$array1=array_fill("a",3,"apple");
print_r($array1);
?>

Output

As array_fill() expects an integer for the index parameter. So, it will raise a warning as shown below.

PHP array_fill() - Warning: array_fill() expects parameter 1 to be int

Conclusion

In this PHP Tutorial, we learned how to create an indexed array of specific size and default value for the items, using PHP Array array_fill() function.