← Back to Chapters

PHP Array_Fill & Array_Fill_Keys

? PHP Array_Fill & Array_Fill_Keys

? Quick Overview

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.

? Key Concepts

  • array_fill() creates indexed arrays with repeated values.
  • array_fill_keys() creates associative arrays using predefined keys.
  • Both functions are useful for default initialization.

? Syntax / Theory

  • array_fill(start_index, count, value)
  • array_fill_keys(keys_array, value)

? Example 1: array_fill()

? View Code Example
// Create an indexed array filled with the same value
<?php
$array = array_fill(0, 5, "apple");
print_r($array);
?>

? Explanation

The function starts at index 0 and fills 5 positions with the value apple.

? Example 2: array_fill_keys()

? View Code Example
// Fill an associative array using predefined keys
<?php
$keys = array("a","b","c");
$array = array_fill_keys($keys,"orange");
print_r($array);
?>

? Explanation

Each key from the $keys array is assigned the value orange.

? Example 3: Negative Indices

? View Code Example
// Use negative index to control array keys
<?php
$array = array_fill(-3,5,"banana");
print_r($array);
?>

? Explanation

The array begins at index -3 and continues sequentially.

➕ Example 4: Combined Usage

? View Code Example
// 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);
?>

? Visual Flow (Concept Diagram)

Keys / Index Fill Function Final Array

? Use Cases

  • Initializing scoreboards or counters
  • Default configuration arrays
  • Temporary placeholder data
  • Pre-filling forms or datasets

✅ Tips & Best Practices

  • Use array_fill() for numeric indexes.
  • Use array_fill_keys() for associative arrays.
  • Keep values simple to avoid memory overhead.

? Try It Yourself

  • Create an array of 5 elements starting at index 1 filled with "grape".
  • Build a student-score map using array_fill_keys().
  • Experiment with negative starting indexes.
  • Modify values after initialization.