PHP array_fill() function
The array_fill()
function in PHP is used to create an array and fill it with a specified value. It allows you to generate an array where all the elements have the same value. This can be useful in various scenarios, such as initializing an array with default values.
Syntax:
Parameters:
- $start_index: The index at which to start filling the array. This can be positive (starting from the beginning) or negative (starting from the end).
- $count: The number of elements to fill in the array. If this value is less than or equal to 0, the function returns an empty array.
- $value: The value that will be used to fill the array. This can be any data type (e.g., integer, string, object, etc.).
Return Value:
- The function returns an array filled with the specified value for the given number of elements, starting at the specified index.
Example 1: Basic Usage
Output:
In this example, the array is filled with 5 occurrences of the value "apple"
, starting at index 0.
Example 2: Negative Start Index
You can use a negative $start_index
to fill an array starting from the end.
Output:
In this case, the array starts filling from index -3
and fills 4 positions, with each position containing the value "banana"
.
Example 3: Zero or Negative Count
If the $count
parameter is 0 or negative, array_fill()
will return an empty array.
Output:
Example 4: Different Data Types
The value used to fill the array can be of any data type, including numbers, strings, or even objects.
Output:
In this example, the array is filled with three occurrences of the integer 100
.
Practical Usage:
array_fill()
is useful for:- Initializing arrays with default values (e.g., creating placeholders).
- Setting up arrays to later be filled with data dynamically.
- Creating predefined structures for testing or prototyping.
Limitations:
- If you need to fill an array with key-value pairs, use other functions like
array_fill_keys()
instead ofarray_fill()
, which only allows for indexed filling.
Summary:
array_fill($start_index, $count, $value)
creates and returns an array where all elements are filled with a specified value.- You can define the number of elements and the starting index.
- It’s a simple yet powerful function for generating arrays with preset values.