$new_array = array_fill ($start_key, $number, $value);
Parameter | DESCRIPTION |
---|---|
$start_key | Required : Integer , starting key number. |
$number | Required: Integer: Number of elements filled. |
$value | Required: value to be used to fill the array. |
$result=array_fill(2,4,'plus2net');
while (list ($key, $val) = each ($result)) {
echo "$key -> $val
";
}
Output is here.
2 -> plus2net
3 -> plus2net
4 -> plus2net
5 -> plus2net
$result=array_fill(-3,4,'plus2net');
//while (list ($key, $val) = each ($result)) { // for PHP 7 or lower version
foreach ($result as $key=>$val) { // PHP 8
echo "$key -> $val <br>";
}
Output
-3 -> plus2net
-2 -> plus2net
-1 -> plus2net
0 -> plus2net
When processing forms with multiple inputs, array_fill() can help initialize empty fields with default values. This is useful to avoid undefined index errors.
$input_fields = array_fill(0, 5, '');
print_r($input_fields);
This will create an array of 5 elements, each initialized to an empty string, which can be assigned to form inputs.
While array_fill() creates indexed arrays, we can simulate an associative array by using custom keys:
$keys = ['name', 'email', 'age'];
$filled_array = array_combine($keys, array_fill(0, count($keys), 'default'));
print_r($filled_array);
This example fills an array with predefined keys, assigning 'default' to each key.
In some cases, you may want to fill an array only under certain conditions. This example demonstrates filling an array if a value meets a condition:
$numbers = range(1, 10);
$filled_array = array_map(function($num) {
return $num % 2 == 0 ? 'even' : $num;
}, $numbers);
print_r($filled_array);
This creates an array of numbers but replaces even numbers with the string 'even'.
You can also use array_fill() to create multi-dimensional arrays by nesting the function:
$matrix = array_fill(0, 3, array_fill(0, 3, 0));
print_r($matrix);
This creates a 3x3 matrix (two-dimensional array) filled with zeros.
In performance-critical applications, preallocating arrays can help optimize memory usage, especially when you know the array's size in advance:
$preallocated_array = array_fill(0, 1000000, null);
This creates a large array of 1,000,000 elements, each initialized to *null*, which can be filled later.
We can combine array_fill() with other array functions for more flexibility:
$default_values = array_fill(0, 5, 'N/A');
$additional_values = ['age' => 25, 'name' => 'John'];
$final_array = array_merge($additional_values, $default_values);
print_r($final_array);
This merges predefined values with default ones, ensuring that the array has all required keys.