Passing Javascript Arrays to PHP

Needed to pass a simple Javascript array to a PHP script for some back end processing. Here’s a quick and dirty way of doing so by ‘serializing’ the javascript array as a string to send along in your request, and then splitting this string into tokens to create a PHP array.

Javascript: (using jquery javascript library)

var selections = new Array;
var userSelections;
$('#multipleSelection :selected').each(function(i, selected) {
selections[i] = $(selected).val();
userSelections = selections.join(",");

In the PHP script, it’s just a matter of processing the individual elements of the array. Depending on how you sent the ajax request (POST/GET).

PHP Example:

$selectionsArray = explode(',',$_GET['userSelections']);

foreach($selectedArray as $index=>$value) {
echo $index ." = ".$value;