array_fill_keys

array_fill_keys(array $keys, mixed $value): array

Fill from a key array: the values of $keys become the keys and one shared $value fills the whole table (the mirror direction of array_fill, which fills by index range); numeric-string keys coerce to int per PHP convention.

C C23

C23
#include <stdio.h>

/* C has no associative array: parallel arrays make the key->value table */
int main(void) {
    const char *keys[] = {"draft", "review", "published"};
    int values[3] = {0}; /* zero-initialized: every key starts false */
    values[1] = 1; /* review := true */
    for (int i = 0; i < 3; i++) {
        printf("%s=%d\n", keys[i], values[i]);
    }
    return 0;
}
Output
draft=0
review=1
published=0

C++ C++26

C++26
#include <iostream>
#include <map>
#include <string>

int main() {
    // std::map seeded from the key list: every key gets the same value
    std::map<std::string, bool> flags;
    for (const std::string k : {"draft", "review", "published"}) flags[k] = false;
    flags["review"] = true;
    for (const auto &[k, v] : flags) std::cout << k << '=' << v << '\n';
    std::cout << "size=" << flags.size() << '\n';
    return 0;
}
Output
draft=0
published=0
review=1
size=3

C# v11.0.100

v11.0.100
using System;
using System.Linq;

var keys = new[] { "draft", "review", "published" };
// ToDictionary mirrors array_fill_keys: every key gets the same value
var flags = keys.ToDictionary(k => k, k => false);
flags["review"] = true;
Console.WriteLine(string.Join(",", flags.Select(kv => $"{kv.Key}:{kv.Value}")));
Console.WriteLine($"count={flags.Count}");
Output
draft:False,review:True,published:False
count=3

Go v1.27.4

v1.27.4
package main

import "fmt"

func main() {
	// no fill-keys builtin: seed a map from the key list
	flags := map[string]bool{}
	for _, k := range []string{"draft", "review", "published"} {
		flags[k] = false
	}
	flags["review"] = true
	fmt.Println(flags)
	fmt.Println("len=", len(flags))
}
Output
map[draft:false published:false review:true]
len= 3

Java v27.0.1

v27.0.1
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // no fill-keys builtin: seed a LinkedHashMap from the key list
        Map<String, Boolean> flags = new LinkedHashMap<>();
        for (String k : List.of("draft", "review", "published")) flags.put(k, false);
        flags.put("review", true);
        System.out.println(flags);
        System.out.println("size=" + flags.size());
    }
}
Output
{draft=false, review=true, published=false}
size=3

JavaScript v26.13.1

v26.13.1
// no direct builtin: Object.fromEntries(keys.map(k => [k, value])) is the idiom
const flags = Object.fromEntries(["draft", "review", "published"].map((k) => [k, false]));
flags.review = true;
console.log(JSON.stringify(flags));
console.log(JSON.stringify(Object.fromEntries(["a", "5"].map((k) => [k, 0]))));
Output
{"draft":false,"review":true,"published":false}
{"5":0,"a":0}

PHP v8.6.0

v8.6.0
// array_fill_keys mirrors array_fill: keys come from an array, every key
// shares one value; numeric strings in keys are coerced to ints.
$flags = array_fill_keys(['draft', 'review', 'published'], false);
$flags['review'] = true;
echo json_encode($flags), "\n";
echo 'numeric keys coerced=', json_encode(array_fill_keys(['a', '5'], 0));
Output
{"draft":false,"review":true,"published":false}
numeric keys coerced={"a":0,"5":0}

Python v3.15.2

v3.15.2
# dict.fromkeys is the native counterpart: keys from an iterable, one shared value
flags = dict.fromkeys(["draft", "review", "published"], False)
flags["review"] = True
print(flags)
print("numeric-key list=", dict.fromkeys(["a", 5], 0))
Output
{'draft': False, 'review': True, 'published': False}
numeric-key list= {'a': 0, 5: 0}

Rust v1.99.1

v1.99.1
// no fill-keys builtin: seed a HashMap from the key list
use std::collections::HashMap;

fn main() {
    let mut flags: HashMap<&str, bool> =
        ["draft", "review", "published"].iter().map(|&k| (k, false)).collect();
    flags.insert("review", true);
    println!("len={}", flags.len());
    println!("review={} draft={}", flags["review"], flags["draft"]);
}
Output
len=3
review=true draft=false

TypeScript v26.13.1

v26.13.1
// no direct builtin: Object.fromEntries(keys.map(k => [k, value])) is the idiom
const flags: Record<string, boolean> = Object.fromEntries(
  ["draft", "review", "published"].map((k) => [k, false]),
);
flags.review = true;
console.log(JSON.stringify(flags));
const counters: Record<string, number> = Object.fromEntries(
  ["a", "5"].map((k) => [k, 0]),
);
console.log(JSON.stringify(counters));
Output
{"draft":false,"review":true,"published":false}
{"5":0,"a":0}

Language differences

PHP: array_fill_keys(keys, value) uses the VALUES of the key array as keys of the new table and fills them all with one shared value — the mirror of array_fill(start, count, value) (index-range filling, see that entry): one takes a key list, the other an index range, with the parameter direction reversed; typical uses: counter/flag-table initialization (array_fill_keys(range('a','z'), 0), field-whitelist defaults); traps: numeric strings in the key array coerce to int ("5" becomes 5, consistent with all PHP array-key rules), duplicate keys overwrite with the later one (before 8.0 the later one landed BEFORE the earlier — order differed; since 8.0 it uniformly overwrites keeping the first position), and value is one shared reference (objects mean every key points at the same instance — clone in a loop if needed); distinguish from array_combine(keys, values): combine PAIRS two arrays, fill_keys shares one value across one array.

C: no associative array — parallel arrays (keys[] + values[]) hand-build the table; int values[3] = {0} zero-init is the hand-written version of "fill with one initial value".

C++: a std::map seeding loop (the example) — flags[k] = false inserts and assigns in one step; ordered map iterates sorted (draft/published/review alphabetically); for insertion order use std::vector<std::pair>.

C#: keys.ToDictionary(k => k, k => false) (the example) is a one-liner — note ToDictionary THROWS on duplicate keys (unlike PHP's silent overwrite); overwrite semantics need GroupBy-take-first or a hand loop; .NET Dictionary preserves insertion order in practice but not by contract, so be careful when output depends on it.

Go: no builtin — a for-range loop seeds the map (the example); fmt prints maps sorted by key (since Go 1.12, which this deterministic output relies on); the zero-value map bonus is that flags[k] on a missing key yields the zero value (false), so "initial fill" holds naturally on the read side.

Java: no builtin — LinkedHashMap (the example) with a seeding loop; a HashMap would iterate unordered (unstable output), so the example uses LinkedHashMap to keep insertion order and deterministic output.

JavaScript: Object.fromEntries(keys.map(k => [k, value])) (the example) in one line; note the JSON output hoists integer-like keys ("5") first — JS engines keep integer keys in a separate ordering slot (echoing PHP's numeric-key coercion but WITHOUT coercing types: "5" stays a string key).

Python: dict.fromkeys(iterable, value) (the example) is the only native one-to-one API across the ten languages (signature and semantics fully aligned); the shared-value trap applies equally: fromkeys with a mutable object (like []) makes every key reference the same list — a famous FAQ moment; use a dict comprehension to build a fresh object per key.

Rust: no builtin — keys.iter().map(|&k| (k, false)).collect() (the example) gathers an iterator into a HashMap; a missing key reads as Option (flags.get(k)), unlike Go's zero-value philosophy; HashMap iteration is unordered, so the example reads by key to stay deterministic.

TypeScript: same as JavaScript; Record<string, T> types the filled result and constrains key/value types at compile time.

Teaching anchor: the fill direction where KEYS come from data and VALUES from a constant — contrasted three ways against array_fill (values from a constant, keys a mechanical range) and array_combine (both from data); a second anchor is the shared-value trap: except C (parallel arrays store separately), every language's fill semantics is "one shared reference" — build a new object per key when values are objects/lists.