Equivalent of PHP’s array_combine() function

Save to StumbleUpon Stumble Upon it!   Save to Del.icio.us Save to Del.icio.us

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">
<HTML>
 <HEAD>
  <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">

<SCRIPT LANGUAGE="JavaScript">

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;
	}
	else
	{
		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

document.write("Array<br>{<br>");

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

document.write("}<br>");

</SCRIPT>

</HEAD>
<BODY>
</BODY>
</HTML>

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

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

 The archive is made using WinZip 12.0. If you're having problems unzipping it, consider using WinRar, WinAce or a similar software to extract the files from the archive.

Be notified when we have new posts by subscribing to  RSS BitRepository RSS Feed.
   Save to StumbleUpon   

Comment on this post!

Subscribe to BitRepository RSS Feed
[Advertise with us]