PHP array_fill_keys() Function

PHP

PHP array_fill_keys() - Fill Keys with Values

Category: Array | Subcategory: array_fill_keys()

SEO Keywords: PHP array_fill_keys, fill array keys, PHP array key fill, create array from keys, PHP key-value array

Introduction

The array_fill_keys() function in PHP is a powerful utility designed to create arrays with specific keys, all assigned the same value. Unlike traditional array initialization where keys and values are manually specified, array_fill_keys() simplifies the process by taking an array of keys and a single value to fill every key. This makes it an efficient choice for situations where you need uniform values across multiple keys β€” such as initializing configuration arrays, placeholders, or default settings.

Prerequisites

  • Basic understanding of PHP syntax and array structures.
  • PHP version 5.2.0 or higher (the version from which array_fill_keys() is supported).
  • A working PHP environment (local or server) to run PHP scripts.

Setup Steps

  1. Ensure PHP is installed on your machine or server.
  2. Create a new PHP file, for example, fill_keys_example.php.
  3. Open the file in your preferred code editor.
  4. Use the provided examples below to test the array_fill_keys() function.
  5. Run the PHP script via command line (php fill_keys_example.php) or through a web server setup.

Understanding the array_fill_keys() Function

array_fill_keys() syntax:

array array_fill_keys ( array $keys , mixed $value )
  • $keys: An array of keys which you want to use in your resulting array.
  • $value: The value with which each key in the resulting array will be filled.

The function returns a new array where every key from $keys is set to the provided $value.

Examples

Example 1: Basic Usage

<?php
$keys = ['id', 'name', 'email'];
$value = null;

$result = array_fill_keys($keys, $value);
print_r($result);
?>

Output:

Array
(
    [id] => 
    [name] => 
    [email] => 
)

Here, the keys for the resulting array are defined, and all values are set to null.

Example 2: Filling with a String Value

<?php
$keys = ['username', 'password', 'role'];
$value = 'unknown';

$result = array_fill_keys($keys, $value);
print_r($result);
?>

Output:

Array
(
    [username] => unknown
    [password] => unknown
    [role] => unknown
)

This example fills the keys with the string "unknown".

Example 3: Using Numbers as Keys

<?php
$keys = [10, 20, 30];
$value = 0;

$result = array_fill_keys($keys, $value);
print_r($result);
?>

Output:

Array
(
    [10] => 0
    [20] => 0
    [30] => 0
)

Numeric keys are handled normally by array_fill_keys().

Best Practices

  • Key Uniqueness: Make sure the keys array contains unique keys since duplicate keys in an array will be overwritten.
  • Value Types: The value parameter can be any valid PHP data type, including null, strings, numbers, or even objects.
  • Immutable Use: Use array_fill_keys() to initialize arrays before populating or updating, ensuring predictable array structure.
  • Combine with Other Functions: Use alongside array_keys() or array manipulation functions for dynamic key generation.

Common Mistakes

  • Passing Non-array as Keys: The first argument must be an array; passing a string or number will cause an error.
  • Ignoring Duplicated Keys: Duplicate keys in the $keys array will be overwritten silently, potentially causing unexpected results.
  • Using Empty Keys Array: Passing an empty array as keys returns an empty array, which might be overlooked in logic.
  • Using Non-scalar Values for Keys: Keys must be integers or strings; using arrays or objects as keys will cause a warning or error.

Interview Questions

Junior Level

  • Q1: What does the PHP function array_fill_keys() do?
    A: It creates a new array with the specified keys, filling each key with the same value.
  • Q2: What arguments does array_fill_keys() require?
    A: It takes an array of keys and a single value to assign to all those keys.
  • Q3: Can array_fill_keys() fill an array with different values for each key?
    A: No, it fills all keys with the same single value.
  • Q4: What type of array keys can you pass to array_fill_keys()?
    A: Keys should be strings or integers.
  • Q5: What PHP version introduced array_fill_keys()?
    A: PHP 5.2.0

Mid Level

  • Q1: What happens if you pass duplicate keys to array_fill_keys()?
    A: The duplicate keys will be overwritten, and only the last occurrence will remain in the array.
  • Q2: How can array_fill_keys() be used with array_keys()?
    A: You can retrieve keys from an existing array with array_keys() and fill them with a default value using array_fill_keys().
  • Q3: Is array_fill_keys() more efficient than looping through keys to assign values? Why?
    A: Yes, it's more concise and optimized internally since it creates and fills the array in one function call.
  • Q4: Can array_fill_keys() accept objects or arrays as the value parameter?
    A: Yes, it can accept any type of value, including objects or arrays.
  • Q5: What would array_fill_keys([], 'test') return?
    A: It would return an empty array.

Senior Level

  • Q1: How would you handle dynamic creation of an associative array with keys from a database and default values using array_fill_keys()?
    A: Fetch keys (e.g., column names or IDs) into an array and pass it with a default value to array_fill_keys() for initialization before processing.
  • Q2: What are the limitations of array_fill_keys() in terms of data types for keys and how does PHP handle invalid keys?
    A: Keys must be scalars (strings or integers); passing arrays or objects results in warnings or errors as PHP cannot use them as array keys.
  • Q3: Can you suggest an alternative approach if you need to fill different values for each key instead of a single uniform value?
    A: Use a loop or array_combine() with separate keys and values arrays to create an array with unique values per key.
  • Q4: How can array_fill_keys() impact memory and performance in large arrays? Should it be used in high-load environments?
    A: It is efficient for bulk initialization but may consume memory proportional to the keys array size. For very large arrays, consider lazy loading or generators to optimize performance.
  • Q5: How does PHP internally handle the filling operation when using array_fill_keys() compared to manual loops?
    A: Internally, array_fill_keys() likely allocates memory for the final array once and fills keys with the same value efficiently, whereas loops may have overhead in repeated assignments.

Frequently Asked Questions (FAQ)

Q1: Can array_fill_keys() handle numeric and string keys together?

A: Yes, you can pass a mixed array of numeric and string keys, and the function will handle both correctly.

Q2: What happens if the keys array contains duplicate keys?

A: Duplicates are overwritten silently, and the array will only contain a unique set of keys.

Q3: Can I fill keys with different values using array_fill_keys()?

A: No. array_fill_keys() fills all keys with the same single provided value. Use alternative methods for different values.

Q4: Is array_fill_keys() mutable or does it return a new array?

A: It returns a new array without modifying the original keys array.

Q5: Are keys restricted to just strings and integers?

A: Yes. Passing non-scalar types like objects or arrays as keys will raise warnings or errors.

Conclusion

The array_fill_keys() function is a simple yet effective PHP tool for creating associative arrays with uniform values assigned to specific keys. It reduces boilerplate code and makes array initialization cleaner and easier to maintain. Understanding and applying this function will improve your ability to manipulate arrays efficientlyβ€”especially in projects dealing with configuration setups, placeholder data, or default states. With careful attention to best practices, common pitfalls, and appropriate use cases, array_fill_keys() can become a handy component in your PHP array toolkit.

As a PHP array builder specialist with over 12 years of experience, I recommend incorporating array_fill_keys() in your everyday PHP projects where applicable to enhance your code's readability and efficiency.