Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Fill an array with values with specifying keys

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 82
    Comment on it

    If you want to fill the values in array with specifying keys then you can use the pre-defined function "array_fill_keys()" means in this function you pass 2 array as parameter, the values of first array used as key of new array and second array used as values of new array. Here are some example which will explain you array_fill_keys() function-

    <?php
    $keys = array('foo', 5, 10, 'bar');
    $a = array_fill_keys($keys, 'arrayValue');
    print_r($a);
    ?>
    

    Output:

    Array
    (
        [foo] => arrayValue
        [5] => arrayValue
        [10] => arrayValue
        [bar] => arrayValue
    )
    

    here is another example which will clear more your doubt, here an associative array is used as the second parameter of array_fill_keys, then the associative array will be appended in all the values of the first array.

    <?php 
    $array1 = array( 
        "a" => "first", 
        "b" => "second", 
        "c" => "something", 
        "red" 
    ); 
    
    $array2 = array( 
        "a" => "first", 
        "b" => "something", 
        "letsc" 
    ); 
    
    print_r(array_fill_keys($array1, $array2)); 
    ?> 
    

    The output will be-

    Array( 
        [first] => Array( 
            [a] => first, 
            [b] => something, 
            [0] => letsc 
        ), 
        [second] => Array( 
            [a] => first, 
            [b] => something, 
            [0] => letsc 
        ), 
        [something] => Array( 
            [a] => first, 
            [b] => something, 
            [0] => letsc 
        ), 
        [red] => Array( 
            [a] => first, 
            [b] => something, 
            [0] => letsc 
        ) 
    )
    

 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: