In this tutorial, you shall learn about PHP array_fill_keys() function which can create an array with specified keys and a default value, with syntax and examples.

PHP array_fill_keys() Function

The PHP array_fill_keys() function returns an array with specified keys and specific default value for all keys.

Syntax of array_fill_keys()

The syntax of array_fill_keys() function is

array_fill_keys( keys, value)

where

ParameterDescription
keys[mandatory] An array of keys.
value[mandatory] Default value for the keys.

Function Return Value

array_fill_keys() returns the an array filled with keys and default value for each of the keys.

ADVERTISEMENT

Examples

1. Fill array with specified keys and default value

In this example, we will take an array of keys, and a value. We will call array_fill_keys() function, pass the keys and value to it as arguments. The function returns an array with the specified keys and value.

PHP Program

<?php
    $keys = array("apple","banana");
    $value = 100;
    $result = array_fill_keys($keys, $value);
    print_r($result);
?>

Output

PHP array_fill_keys() - Fill Array with Specific Keys and Default Value

2. Warning: array_fill_keys() expects exactly 2 parameters

In this example, we will take an array of keys. We will call array_fill_keys() function, pass only the keys and no value to it as arguments. The function raises a warning that the function array_fill_keys() expects exactly 2 parameters.

PHP Program

<?php
    $keys = array("apple","banana");
    $result = array_fill_keys($keys);
    print_r($result);
?>

Output

Warning: array_fill_keys() expects exactly 2 parameters

Conclusion

In this PHP Tutorial, we learned how to fill an array with specific keys and a default value for them, using PHP Array array_fill_keys() function.