Content · Programming · PHP

PHP array_fill() Function: Usage and Examples

Learn how to use PHP array_fill() to create arrays with repeated values, control starting indexes, and initialize data with practical examples.

2 views Published Oct 16, 2026 Updated Oct 16, 2026 Admin

Sometimes you need to create a PHP array containing several elements with the same initial value. For example, you might want to initialize scores to zero, set default statuses, or prepare empty fields for later updates.

Instead of manually adding each element, PHP provides the array_fill() function.

In this guide, you'll learn how to use array_fill(), control array indexes, and handle common situations.

What Is array_fill() in PHP?

The array_fill() function creates a new array containing a specified number of elements, all initialized with the same value.

Its syntax is:

array_fill(
    int $start_index,
    int $count,
    mixed $value
): array

The function accepts three parameters:

  • $start_index — The numeric index where the array begins.
  • $count — The number of elements to create.
  • $value — The value assigned to each element.

It returns a new array with consecutive integer keys, starting at the specified index.

Example 1: Creating an Array with Repeated Values

Let's create an array containing five zeros.

<?php

$numbers = array_fill(0, 5, 0);

print_r($numbers);

Output:

Array
(
    [0] => 0
    [1] => 0
    [2] => 0
    [3] => 0
    [4] => 0
)

The first argument, 0, specifies the starting index. The second creates five elements, and the third fills them with zero.

You can use other values, including strings, booleans, and arrays:

<?php

$statuses = array_fill(0, 3, "Pending");

print_r($statuses);

Output:

Array
(
    [0] => Pending
    [1] => Pending
    [2] => Pending
)

Example 2: Changing the Starting Index

The first parameter doesn't have to be zero.

<?php

$scores = array_fill(1, 4, 100);

print_r($scores);

Output:

Array
(
    [1] => 100
    [2] => 100
    [3] => 100
    [4] => 100
)

The array starts at index 1 and contains four elements. This can be useful when your application uses one-based numbering.

Using Negative Starting Indexes

PHP also supports negative starting indexes.

<?php

$values = array_fill(-2, 4, "Ready");

print_r($values);

Output in PHP 8+:**

Array
(
    [-2] => Ready
    [-1] => Ready
    [0] => Ready
    [1] => Ready
)

Starting with PHP 8.0, negative indexes increment normally. In earlier versions, the index immediately following the first negative key started at zero.

Practical Example: Tracking Weekly Attendance

Imagine you're building an employee attendance tracker.

Initially, every workday should have a status of "Not recorded". As attendance information becomes available, you can update individual entries.

Create a file named attendance.php:

<?php

declare(strict_types=1);

// Define the workdays.

$days = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday"
];

// Initialize all attendance statuses.

$attendance = array_fill(
    0,
    count($days),
    "Not recorded"
);

// Update attendance information.

$attendance[0] = "Present";
$attendance[1] = "Present";
$attendance[2] = "Absent";

// Display the weekly attendance.

echo "<h2>Weekly Attendance</h2>";

echo "<ul>";

foreach ($days as $index => $day) {

    $message = $day . ": " . $attendance[$index];

    echo "<li>" . htmlspecialchars(
        $message,
        ENT_QUOTES,
        "UTF-8"
    ) . "</li>";
}

echo "</ul>";

Browser output:

Weekly Attendance

Monday: Present
Tuesday: Present
Wednesday: Absent
Thursday: Not recorded
Friday: Not recorded

The array_fill() function creates five initial statuses automatically.

Each element can then be updated independently without changing the remaining entries.

This approach also works for initializing test results, task progress, and other collections that require default values.

Handling Empty Arrays and Invalid Counts

The $count parameter determines how many elements are created.

When the count is zero, PHP returns an empty array:

<?php

$result = array_fill(0, 0, "Pending");

var_dump($result);

Output:

array(0) {
}

However, negative counts are invalid. In PHP 8+, they produce a ValueError.

<?php

try {
    $result = array_fill(0, -3, "Pending");
} catch (ValueError $error) {
    echo "Invalid number of elements.";
}

Output:

Invalid number of elements.

When the count comes from user input, validate it before creating the array. A very large count can also consume substantial memory.

array_fill() vs array_fill_keys()

PHP provides another function called array_fill_keys(), but it serves a slightly different purpose.

Function Purpose
array_fill() Creates a specified number of elements with consecutive numeric keys.
array_fill_keys() Creates elements using a supplied list of keys.

For example, if you need named keys instead of numeric indexes:

<?php

$fields = ["name", "email", "phone"];

$data = array_fill_keys($fields, null);

print_r($data);

Output:

Array
(
    [name] =>
    [email] =>
    [phone] =>
)

Use array_fill() for consecutive numeric indexes and array_fill_keys() when you already know the desired array keys.

Key Takeaways

  • array_fill() creates an array containing repeated values.
  • The starting index and number of elements are configurable.
  • Values can be integers, strings, booleans, arrays, or other PHP types.
  • PHP 8+ supports consecutive negative indexes.
  • A count of zero returns an empty array; invalid counts throw a ValueError in PHP 8+.
  • Use array_fill_keys() when you need specific array keys.

The array_fill() function is a convenient way to initialize PHP arrays with default values. It reduces repetitive code and is useful whenever your application needs a predictable starting structure for its data.

For more information, see the official PHP array_fill() documentation.

Share this resourceSend this page to someone who may find it useful.