Sebastian
Sebastian

Reputation: 3626

Print value from PHP key value pair

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?

Upvotes: 0

Views: 677

Answers (2)

Jason OOO
Jason OOO

Reputation: 3552

You can also try this:

$data = json_decode($_POST['data'], true)['id']

Upvotes: 1

John Conde
John Conde

Reputation: 219884

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

Upvotes: 4

Related Questions