PHP array_fill() - Fill Arrays with Values
The array_fill() function in PHP is a powerful and efficient way to initialize arrays with a specific value repeated over a range of keys. Whether you need to pre-populate an array for later processing, set default values, or create placeholders, this built-in function can simplify your code significantly.
Prerequisites
- Basic understanding of PHP syntax and arrays
- PHP environment (version 4 or higher, as
array_fill()has been available since PHP 4) - A code editor or IDE to write and test PHP scripts
Setup
To get started, ensure you have PHP installed on your system. You can run your PHP scripts via the command line, local server (like XAMPP, MAMP), or any online PHP sandbox.
Example to check PHP version:
php -v
Understanding array_fill()
The array_fill() function creates a new array filled with a specified value, starting from a given index. Unlike some other functions that start at index 0, you control the start index.
Function Signature
array_fill(int $start_index, int $count, mixed $value): array
$start_index: The first index of the array (can be negative)$count: The number of elements to fill$value: The value to fill each element with- Returns an array filled with
$countelements at sequential keys starting from$start_index
Examples
Example 1: Creating a simple array filled with one value
<?php
$array = array_fill(0, 5, "apple");
print_r($array);
?>
Output:
Array
(
[0] => apple
[1] => apple
[2] => apple
[3] => apple
[4] => apple
)
Explanation:
This creates an array with 5 elements, all with the value "apple". Starting index is 0.
Example 2: Using a negative start index
<?php
$array = array_fill(-3, 4, 100);
print_r($array);
?>
Output:
Array
(
[-3] => 100
[-2] => 100
[-1] => 100
[0] => 100
)
Explanation:
This array starts at index -3 and fills 4 elements with 100.
Example 3: Filling an array with default boolean values
<?php
$flags = array_fill(0, 3, false);
print_r($flags);
?>
Output:
Array
(
[0] =>
[1] =>
[2] =>
)
Note: In PHP, false is printed empty by default.
Example 4: Using array_fill() for multidimensional arrays (manual nesting)
<?php
$matrix = array_fill(0, 3, array_fill(0, 2, 0));
print_r($matrix);
?>
Output:
Array
(
[0] => Array
(
[0] => 0
[1] => 0
)
[1] => Array
(
[0] => 0
[1] => 0
)
[2] => Array
(
[0] => 0
[1] => 0
)
)
Note: The inner arrays are copies of the same array; modifying one inner array will affect others due to PHP’s copy-on-write. Use a loop if you want independent inner arrays.
Best Practices
- Use
array_fill()when you need fixed-size arrays with default values. - Be cautious when filling multi-dimensional arrays with nested
array_fill(). Use loops or functions likearray_map()to avoid shallow copies. - Use negative start indexes wisely when your use-case requires indexing from negative or custom base indexes.
- Remember that the
$countparameter must be a positive integer; zero or negative values cause warnings or unexpected outcomes.
Common Mistakes
- Passing a non-integer or negative
$count— this triggers a warning. - Assuming
array_fill()creates deeply independent nested arrays when using it for multidimensional arrays. - Not setting the correct start index, leading to unexpected keys.
- Confusing
array_fill()witharray_fill_keys()(which fills arrays based on explicit key lists).
Interview Questions
Junior Level
-
Q1: What does the
array_fill()function do in PHP?
A: It creates a new array of specified size filled with the given value. -
Q2: What parameters does
array_fill()accept?
A: A start index, a number of items to fill, and the fill value. -
Q3: Can the start index in
array_fill()be negative?
A: Yes, it can be any integer including negative values. -
Q4: What happens if you pass zero as the count parameter?
A: The function returns an empty array. -
Q5: How do you fill 10 elements with the value 0 starting from index 1?
A: Usearray_fill(1, 10, 0);.
Mid Level
-
Q1: How does
array_fill()differ fromarray_fill_keys()?
A:array_fill()fills sequential numeric keys starting at a start index;array_fill_keys()fills specified keys with a value. -
Q2: Is it safe to use
array_fill()to create multidimensional arrays?
A: It depends; nested arrays created viaarray_fill()will reference the same array unless handled carefully. -
Q3: What will happen if you provide a negative value for the count parameter?
A: PHP will emit a warning and return FALSE. -
Q4: How do negative start indexes affect the resulting array keys?
A: The array indexes begin from the negative number you specify and increment sequentially. -
Q5: Can
array_fill()fill arrays with objects?
A: Yes, it can fill an array with references to the same object instance.
Senior Level
-
Q1: Explain the implications of using
array_fill()for nested arrays with respect to references and copying.
A: Nested arrays created witharray_fill()point to the same memory reference. Modifying one element affects all because PHP performs a shallow copy until modification. -
Q2: How can you create a deeply nested array with independent inner arrays using
array_fill()?
A: Use loops or array functions likearray_map()insidearray_fill()to create new instances for each nested element. -
Q3: Discuss potential performance benefits of using
array_fill()over manual loops for initializing arrays.
A:array_fill()is implemented internally in PHP and optimized, generally faster and less verbose than manual loops. -
Q4: When would you prefer
array_fill_keys()overarray_fill()in PHP array initialization?
A: Usearray_fill_keys()when you want to fill non-sequential or specific keys rather than a range of numeric indexes. -
Q5: How do you handle filling large arrays with complex objects using
array_fill()without unintended shared references?
A: Create each object instance separately, possibly using loops or generators, sincearray_fill()assigns the same object reference to all elements.
Frequently Asked Questions (FAQ)
Q1: Can I use array_fill() to fill associative arrays?
No. array_fill() creates numerically indexed arrays starting at the given start index. For associative arrays, consider array_fill_keys().
Q2: What if I want to fill an array with a value but do not know the start index?
Typically, use 0 as a start index. If you need custom keys, use array_fill_keys().
Q3: What if I pass a float as $count?
PHP will cast it to an integer but it's best practice to always pass integers to avoid unexpected behavior.
Q4: Does array_fill() preserve keys if the start index is negative?
Yes, keys will start from the negative index and increment sequentially. The keys are preserved as specified.
Q5: Can I fill an array of resources using array_fill()?
Yes, but like objects, all elements will reference the same resource handle.
Conclusion
The PHP array_fill() function is an excellent tool for efficiently creating arrays initialized with specific values, especially when default values or placeholders are needed. Its flexibility in starting index and ability to fill with any data type make it valuable in a variety of scenarios. Remember to handle nested arrays carefully to avoid unintended shared references and leverage array_fill() in combination with other array functions for maximum control.
Mastering array_fill() helps build cleaner, more readable, and efficient array initialization patterns in PHP.