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?
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?
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.
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);
AJAX it. Just like anything else you want to send to the server without a full page reload.
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.