PHP Array array_fill_keys() Function (With Examples)

In this tutorial, we will learn about the PHP array_fill_keys() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_fill_keys() Function

The array_fill_keys() function is used to fill a given array with a value where keys are specified. We will use an array that contains keys, all these keys will be filled with the value and return a new array.

Syntax

The syntax of the array_fill_keys() function:

array_fill_keys(keys, value) : array

Parameters

The parameters of the array_fill_keys() function:

  • keys is an array and its value will be used as keys for the new array.
  • value to be filled for the keys.

Return Value

The return type of this method is array, it returns the filled array.

Sample Input/Output

Input:
$keys = array("Name", "Age", "Gender", "Address"); 
value = "N/A"

Function call:
array_fill_keys($keys, "N/A");
Output:
Array
(
    [Name] => N/A
    [Age] => N/A
    [Gender] => N/A
    [Address] => N/A
)

PHP array_fill_keys() Function Example

<?php
//keys (creating array)
$keys = array("Name", "Age", "Gender", "Address");

//creating an array with these keys
//and, filling all keys with default value
$arr = array_fill_keys($keys, "N/A");

print_r ($arr);
?>

Output

The output of the above example is:

Array
(
    [Name] => N/A
    [Age] => N/A
    [Gender] => N/A
    [Address] => N/A
)

To understand the above example, you should have the basic knowledge of the following PHP topics:

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.