-2

How can I convert a javascript array to a php array??

I have a javascript array which I want to put the values into a php array please help me?

How would I go about doing this?

John Smith
  • 1,089
  • 3
  • 18
  • 37
  • 2
    Please use the search (I'm writing from my phone otherwise I would already have provided a duplicate... (I'm sure this was asked before)) – Felix Kling Mar 26 '12 at 22:38
  • Take a look at this SO answer http://stackoverflow.com/questions/6330830/how-to-convert-javascript-array-to-php-array – The Alpha Mar 26 '12 at 22:47

4 Answers4

5

You would typically convert the array to a JSON string with JSON.stringify, then make an AJAX request to the server, receive the string parameter and json_decode it to get back an array in the PHP side.

Jon
  • 428,835
  • 81
  • 738
  • 806
2

here is the (very) basic idea.

javascript

var arr=your array;
var str;
for(var i=0; i<arr.length; i++) {

    str+='&array_items[]='+arr[i];
}
document.location.href='url.php?'+str;

php

for ($i=0; $i<count($_GET['array_items']); $i++){ 

    $arr[] = $_GET['array_items'][$i];

}

//display php array on page
print_r($arr);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Johnny Craig
  • 4,974
  • 2
  • 26
  • 27
0

AJAX it. Just like anything else you want to send to the server without a full page reload.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

You could convert the javascript to a PHP object too...

/**
* Takes a json encoded string and turns it into a PHP object
* 
* @param string string
* @return object
*/
public static function jsonToPhp($string)
{
    $obj = json_decode(stripslashes($string));
    if (!is_object($obj))
    {
        $obj = json_decode($string);
        if (!is_object($obj))
        {
            print "Cannot convert $string to an object";
                            return NULL;
        }
    }
    return $obj;
}

Requires that your javascript be converted to json.