Question

I have a key/value pair passed from Javascript via $.post as data : user_id.

I've brought it into PHP with $data = $_POST['data'] and when I vardump() that I get {"id":"1"}" as expected. However, I'd like to just access the value of 1.

How would I do that?

Was it helpful?

Solution

It's just JSON. Use json_decode() to turn it into an object (or an array if you so choose) and then get the value of ID using standard object member variable access methods:

$data = json_decode($_POST['data']);
echo $data->id;

Demo

If you're using PHP 5.4+ (using array syntax and array dereferencing):

echo json_decode('{"id":"1"}', true)['id'];

Demo

OTHER TIPS

You can also try this:

$data = json_decode($_POST['data'], true)['id']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top