Equivalent of PHP’s array_combine() function
Posted on October 15, 2008, Filled under JavaScript,
Bookmark it
Thanks for visiting our website! We regularly publish posts like this one. If you are interested in receiving the latest updates as soon as they are posted, please consider subscribing to the RSS feed or to our e-mail newsletter.
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
}
Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!
- October 15, 2008
- article by Gabriel C.
- Leave a reply!
Sponsors
Related Posts
-
Equivalent of PHP’s in_array() functionat September 13, 2008 with 4 comments
-
PHP: How to remove empty values from an arrayat May 21, 2008 with 6 comments
-
PHP: Equivalent of trim() Function for Arraysat October 5, 2008 with 2 comments
-
Basic JS Function to Show/Hide (Toggle) an Elementat November 12, 2008 with 1 comment
-
Creating the array_isearch() Functionat November 8, 2008
