Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two arrays together?

Is there a quick way to combine one arrays values as the other array's keys?

Input:

array A => Array (
        [0] => "cat"
        [1] => "bat"
        [2] => "hat"
        [3] => "mat"
    )

array B => Array (
        [0] => "fur"
        [1] => "ball"
        [2] => "clothes"
        [3] => "home"
    )

Expected output:

array C => Array (
        [cat] => "fur"
        [bat] => "ball"
        [hat] => "clothes"
        [mat] => "home"
    )

How could I do that?

like image 994
Mohammad Avatar asked Mar 24 '11 17:03

Mohammad


People also ask

How do I combine two arrays?

In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.

How do you combine two arrays in Python?

You can use the numpy. concatenate() function to concat, merge, or join a sequence of two or multiple arrays into a single NumPy array. Concatenation refers to putting the contents of two or more arrays in a single array.

How do you combine array elements?

Array.prototype.join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Can we combine two arrays in C?

To concate two arrays, we need at least three array variables. We shall take two arrays and then based on some constraint, will copy their content into one single array. Here in this example, we shall take two arrays one will hold even values and another will hold odd values and we shall concate to get one array.


1 Answers

array_combine() will exactly do what you want.

Quoting the manual:

array array_combine ( array $keys , array $values )

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

In your case, you'd have to do something like this:

$array['C'] = array_combine($array['A'], $array['B']);

While of course you could also use various combinations of loops to do that, array_combine() is probably the simplest solution.

like image 53
Pascal MARTIN Avatar answered Sep 27 '22 21:09

Pascal MARTIN