Search code examples
phparraysmultidimensional-arrayarray-merge

PHP how to combine array and create new array


I have 3 arrays like this :

$first = array(
    [0] => 13
    [1] => 66
    [2] => 15
)

$second = array
(
    [0] => append
    [1] => prepend
    [2] => append
)

$third = array
(
    [0] => 2
    [1] => 4
    [2] => 1
)

Now I want to combine these 3 array and create new SINGLE array like this : I want to get value from each array and combine it into one.

$new_array = array(

    [0] = array (
        'page'=>13,
        'position'=>'append'
        'priority'=>'2'
    )
    [1] = array (
        'page'=>66,
        'position'=>'prepend'
        'priority'=>'4'
    )
    [2] = array (
        'page'=>15,
        'position'=>'append'
        'priority'=>'1'
    )
)

How to do this ?


Solution

  • You can use array_map() to traverse multiple arrays(of the same length) and build a new array from them, item by item:

    $first = array(13, 66, 15);
    $second = array('append', 'prepend', 'append');
    $third = array(2, 4, 1);
    
    print_r(
        array_map(
            function($page, $position, $priority) {
                return compact('page', 'position', 'priority');
            },
            $first,
            $second, 
            $third
        )
    );
    

    Though in this case with a trivial structure foreach() might be an alternative.

    Edit: Version 2. Some might argue that this is worse because of readability and hence code maintainability. Thanks to AbraCadaver

    $keys = ['page', 'position', 'priority'];
    
    // Note: The order in $keys and array_map() arguments must be the same
    // On the other hand you only need to type the keys once and it's easy
    // to change the number of arguments :)
    
    print_r(
        array_map(
            function(...$args) use ($keys) {
                return array_combine($keys, $args);
            },
            $first,
            $second, 
            $third
        )
    );
    

    Edit: Version 3. Using slightly more modern PHP (7.4) with arrow functions:

    print_r(
        array_map(
            fn(...$args) => array_combine($keys, $args),
            $first,
            $second, 
            $third
        )
    );