PHP array_fill_keys() Function with Example

PHP array_fill_keys() Function: Here, we will find out about the array_fill_keys() work with example in PHP.

PHP array_fill_keys() Function

array_fill_keys() work is utilized to fill a given cluster with a value where keys are indicated. We will utilize a cluster that contains keys, every one of these keys will be loaded up with the value and return another exhibit.

Syntax:

array_fill_keys(keys, value) : array

Here,

  • keys is an exhibit and its value will be utilized as keys for the new cluster.
  • value to be filled for the keys.

Example:

    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 Code:

<?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:

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

Leave a Comment

error: Alert: Content is protected!!