Convert JavaScript Array to PHP Array
At times we find ourselves needing to convert JavaScript arrays to PHP arrays, usually because we have to get this data into a MySQL table. That was our particular need. If you don't know how to insert data into MySQL tables, check out some of the PHP-related pages on this website. Here we'll concentrate on the array conversion.
First let's note that to get JavaScript values into PHP, we POST them from a form, since that is more secure than the GET method. It's tedious to deal with a form's hidden fields if their names are array element names and the values array values, but easy to deal with a form's hidden fields if there's only one and the value is simply a string.
To that end we take a simple JavaScript array called colors(), then use the join method to concatenate all these array values into a string. Note that in order to use JavaScript methods at all, we first inserted an onSubmit event into the form tag that ran the function insertarrayintohiddenformfield() when we pressed the submit button. So we use our join method to "stingify" the array prior to sticking that string into the form's hidden input field, a field with the name "color". Note we show the array in an alert box so you can better see what's happening. We POST this string to PHP (on this page) and use the PHP explode() function to make it into a PHP array, and we print out the array with PHP echo statements.
Try out convert-javascript-array-to-PHP-array.php
<?php
$ar = $_POST['color'];$colors = explode(",",$ar);
if (isset($ar)){echo "PHP array \$colors()<BR>";
for ($i=0;$i<10;$i++){
echo "<BR>\$colors[".$i."]: ".$colors[$i];}}
?>
<html>
<head>
<title>Convert JavaScript Array to PHP Array</title>
<meta name="description" content="Convert JavaScript Array to PHP Array">
<meta name="keywords" content="Convert JavaScript Array to PHP Array,php array,javascript array,convert javascript array,dhtml,DHTML">
<script language="javascript">
var colors = new Array('red','blue','black','maroon','silver','green','yellow','orange','gray','purple');
alert("JavaScript array colors()\n\ncolors[0]: "+colors[0]+"\ncolors[1]: "+colors[1]+"\ncolors[2]: "+colors[2]+"\ncolors[3]: "+colors[3]+"\ncolors[4]: "+colors[4]+"\ncolors[5]: "+colors[5]+"\ncolors[6]: "+colors[6]+"\ncolors[7]: "+colors[7]+"\ncolors[8]: "+colors[8]+"\ncolors[9]: "+colors[9]);
function insertarrayintohiddenformfield(){
var color = colors.join();document.Form.color.value=color;}
</script>
</head>
<body>
<div style='position:absolute;top:200px;left:450px'>
<form name="Form" method="post" onsubmit="return insertarrayintohiddenformfield()" action="convert-javascript-array-to-PHP-array.php">
<input name='color' type=hidden>
<input name="convert array" type="submit" value="convert array">
</form>
</div>
</html>