Saturday, July 4th, 2009

Equivalent of PHP’s array_combine() function

by Gabriel on 15/10/08 at 7:59 am

Save to StumbleUpon Stumble Upon it!     Save to Del.icio.us Save to Del.icio.us    Share on Twitter! Share on Twitter!

Greetings! Subscribe to my RSS feed or get my latest post directly in your mailbox. Thanks for visiting!

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
}

Be notified when we have new posts by subscribing to BitRepository RSS Feed.
Support us!Did you like this post?
Please spread the word!
Save to StumbleUpon  Save to Del.icio.us  Share on Twitter!    

Leave a Comment