7

I send this Javascript array into PHP page using form submit {"1":"2","2":"2","3":"2","4":"2"}

Now, I want to convert this array into PHP array, like this

$cars = array("Volvo", "BMW", "Toyota");

So, this is what I tried:

$phparray = str_replace(':', ',', $_POST["questionandanswers"]); // Remove : and replace it with ,
$phparray = str_replace('}', '', $phparray); // Remove }
$phparray = str_replace('{', '', $phparray); // Remove {
echo '<br/>';
echo $phparray; // Output of this is: "1","2","2","2","3","2","4","2"



$questionandanswers = array($phparray); // Now convert it into PHP array

But it is not working. Looks like i cannot put $phparray variable here array($phparray)

But, If instead of putting $phparray variable in array($phparray), If i put the output of $phparray manually, then, it works like: array("1","2","2","2","3","2","4","2")

What's the solution?

2
  • That's not a "Javascript array", that's JSON. Commented Oct 7, 2017 at 8:07
  • 1
    json_decode($json) Commented Oct 7, 2017 at 8:07

2 Answers 2

8

It seems that your form submits a json object to the server so use json_decode with second parameter set to true to convert it to an array.

$php_array=  json_decode($_POST["questionandanswers"],true)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but the thing here is, the object name is not always in a serial order: It can also be like Array ( [3] => 0 [6] => 0 [7] => 0 [11] => 0 ) . So, how to access the object, without knowing it's name?
Just use foreach loop with if statment according to your condition.
Btw, you misspelled json_decode
1

Use json_decode like json_decode($json). It will return an object. If you want array, use json_decode($json, true). See: https://www.php.net/manual/en/function.json-decode.php

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.