Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • array_fill() vs array_fill_keys() in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 516
    Comment on it

    This tutorial explains the difference between array_fill() and array_fill_keys() functions, which are used to initialize or fill an array with values. The main difference is in the method of filling values in array by both functions. The details of each function is given below :


    1. array_fill() : array_fill() function filled an array with value. The function accepts three parameters i.e. start index for array, number of values to insert and value to insert in array, and return an array as result.


    Syntax : array_fill(starting_index, number, value)
    starting_index : Starting index of array.(Required)
    number : Number of elements to be filled in array.(Required)
    value : Value to be filled in array.(Required)


    Note : If starting_index is negative, the returned array start with starting_index and after that index will start from zero.


    Example :

    <?php
     $arr = array_fill(1, 4, 'test');
     print_r($arr);
    ?>
    

    Output : Array ( [1] => test [2] => test [3] => test [4] => test )


    2. array_fill_keys() : array_fill_keys() also used to fill an array with a value on specified keys. This function takes two arguments, first argument is an array for specifying keys and other argument is value to insert.


    Syntax : array_fill_keys(array_keys, value)
    array_keys : An array for specifying key values.(Required)
    value : Value to insert on keys specified by array_keys.(Required)


    Example :

    <?php
     $key = array("a", 1, 5, "b");
     $arr = array_fill_keys($key, "Test");
     print_r($arr); 
    ?>
    

    Output : Array ( [a] => Test [1] => Test [5] => Test [b] => Test )


 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: