Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to create an array in PHP

Tags:

arrays

loops

php

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?

like image 389
Abishek Avatar asked Dec 27 '22 19:12

Abishek


1 Answers

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)
}
like image 85
Tomasz Kowalczyk Avatar answered Jan 08 '23 00:01

Tomasz Kowalczyk