4

I have 2 arrays:

  1. first array is a bunch of keys.
  2. second array is a bunch of values.

I would like to merge them into an associated array in PHP.

Is there a simpler way to do this other than using loops?

2 Answers 2

8

Use array_combine() function:

http://php.net/manual/en/function.array-combine.php

Snippet:

$keys = array('a', 'b', 'c', 'd');
$values = array(1, 2, 3, 4);
$result = array_combine($keys, $values);
var_dump($result);

Result:

array(4) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  int(3)
  ["d"]=>
  int(4)
}
Sign up to request clarification or add additional context in comments.

Comments

2

Use array_combine

Example for docs:

$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);

Should output:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

Check out http://php.net/manual/en/function.array-combine.php

Comments

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.