Equivalent of PHP’s array_combine() function

This is a JavaScript function that works like array_combine() in PHP. Below you have the function and a usage example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  <TITLE>Equivalent of PHP's array_combine() | JavaScript Library</TITLE>
  <META NAME="Author" CONTENT="Bit Repository">

  <META NAME="Keywords" CONTENT="array_combine, php, javascript">
  <META NAME="Description" CONTENT="Equivalent of PHP's array_combine() | JavaScript Library">


var first_array = new Array('green', 'red', 'yellow');

var second_array = new Array('avocado', 'apple', 'banana');

// Alternative way of creating the arrays

var first_array = new Array();

first_array[0] = "green";
first_array[1] = "red";
first_array[2] = "yellow";

var second_array = new Array();

second_array[0] = "avocado";
second_array[1] = "apple";
second_array[2] = "banana";


Parameters: a - array of keys to be used, b - array of values to be used

IMPORTANT: The number of elements for each array must be equal

function array_combine(a, b)
    if(a.length != b.length) 
		return false; 
		new_array = new Array();

		for (i = 0; i < a.length; i++)  
           new_array[a[i]] = b[i];

		return new_array;

var combined_array = array_combine(first_array, second_array);

// Let's print the array in PHP's style


for (key in combined_array)
document.write("[" + key  + "] => " + combined_array[key] + "<br>");




The output will be like the one resulted from the print_r() function in PHP:

echo "<pre>"; print_r($combined_array); echo "</pre>";
[green] => avocado
[red] => apple
[yellow] => banana

Comment via Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *