Equivalent of PHP’s array_combine() function

Posted on October 15, 2008, under JavaScript 

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

* = required fields

  (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)


  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.