0

I have two arrays that look like this:

array 1:

    Array
    (
        [0] => name
        [1] => age
        [2] => job
    )

array 2:

    Array
    (
        [0] => name
        [1] => toan
        [2] => age
        [3] => 21
        [4] => job
        [5] => coder
    )

Now, I would like to take the values from keys 0, 2, 4 and make those values their own keys that point to the values in keys 1, 3, 5 in the array, like so:

Array
(
    [name] => toan
    [age] => 21
    [job] => coder
)

What is simple and fast way to do this?

1
  • Well, implement a small function using a loop and iterate through the second array using array_keys() and array_key_exists() or is_set()... Commented Jan 16, 2014 at 16:32

2 Answers 2

7

Assuming that value is followed by key in array 2, which it would need to be to use array 1 anyway, you don't need array 1:

foreach(array_chunk($array2, 2) as $pair) {
    $result[$pair[0]] = $pair[1];
}
print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

6
array_combine($array1, array_diff($array2, $array1));

Demo

1 Comment

Nice! I normally go for something that doesn't require a loop but that escaped me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.