PHP provides array_fill() and array_fill_keys() to quickly generate arrays filled with default values. These functions reduce repetitive code and help initialize numeric or associative arrays efficiently.
array_fill(start_index, count, value)array_fill_keys(keys_array, value)
// Create an indexed array filled with the same value
<?php
$array = array_fill(0, 5, "apple");
print_r($array);
?>
The function starts at index 0 and fills 5 positions with the value apple.
// Fill an associative array using predefined keys
<?php
$keys = array("a","b","c");
$array = array_fill_keys($keys,"orange");
print_r($array);
?>
Each key from the $keys array is assigned the value orange.
// Use negative index to control array keys
<?php
$array = array_fill(-3,5,"banana");
print_r($array);
?>
The array begins at index -3 and continues sequentially.
// Combine both functions for different structures
<?php
$keys = array("x","y","z");
$filledKeys = array_fill_keys($keys,0);
$filledNumbers = array_fill(0,3,100);
print_r($filledKeys);
print_r($filledNumbers);
?>
array_fill() for numeric indexes.array_fill_keys() for associative arrays.array_fill_keys().