PHP array_fill() Function

Quick summary: The PHP array_fill() function fills an array with values.

PHP array_fill() Syntax

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

PHP array_fill() Basic examples

$result = array_fill(0, 3, 'apple');
print_r($result);
PHP
Output:
Array ( [0] => apple [1] => apple [2] => apple )

Creates an array with 3 elements filled with the same value.

$result = array_fill(5, 2, 100);
print_r($result);
PHP
Output:
Array ( [5] => 100 [6] => 100 )

Start index can be any integer.

PHP array_fill() Real-world usage

$placeholders = array_fill(0, 4, '?');
echo implode(',', $placeholders);
PHP
Output:
?,?,?,?

Generate placeholders for prepared SQL statements.

PHP array_fill() Edge cases

array_fill(0, -1, 'x');
PHP
Output:
Warning

Length must be greater than or equal to 0.

PHP array_fill() Common mistakes

Negative length value

The count parameter cannot be negative.

Incorrect
array_fill(0, -5, 'test');
Correct
array_fill(0, 5, 'test');

Ensure the length argument is a positive integer.

PHP array_fill() Frequently Asked Questions

What does array_fill() do?

Creates an array filled with a specified value.

Syntax of array_fill()?

array_fill(start_index, count, value).

Use case?

Initializing arrays.

Can use negative index?

Yes.

Common mistake?

Wrong count value.

Performance?

Fast.

Return type?

Array.

Handles objects?

Yes.

Safe?

Yes.

Alternative?

Manual loops.

Best practice?

Use for defaults.

Used in testing?

Yes.

PHP array_fill() Related PHP Functions