Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Merge two arrays (same-length) into one associative?

pretty straightforward question actually..

is it possible in PHP to combine two separate arrays of the same length to one associative array where the values of the first array are used as keys in the associative array?

I could ofcourse do this, but I'm looking for another (built-in) function, or more efficient solution..?

function Combine($array1, $array2) {     if(count($array1) == count($array2)) {         $assArray = array();         for($i=0;$i<count($array1);$i++) {             $assArray[$array1[$i]] = $array2[$i];         }         return $assArray;     } } 
like image 621
Ropstah Avatar asked Jul 29 '09 14:07

Ropstah


People also ask

How can I merge two arrays in PHP?

The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.

Does In_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

How can I merge two arrays in PHP without duplicates?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.


2 Answers

array_combine($keys, $values)

PS: Click on my answer! Its also a link!

like image 193
Tyler Carter Avatar answered Oct 14 '22 21:10

Tyler Carter


you need array_combine.

<?php $a = array('green', 'red', 'yellow'); $b = array('avocado', 'apple', 'banana'); $c = array_combine($a, $b);  print_r($c); ?> 
like image 41
OneOfOne Avatar answered Oct 14 '22 21:10

OneOfOne