Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there json_decode($array, TRUE)?

Tags:

json

arrays

php

I send a dictionary as JSON to a server. The dictionary contains only 1 key, that is an array of items:

header('Content-type: application/json');

$request = json_decode(file_get_contents('php://input'));

$array = json_decode($request['array']);

The value for key 'array' is an array, can't be an object.

So, basically these two methods will return the same thing:

$array = json_decode($request['array']);

$array = json_decode($request['array'], TRUE);

Am I right?

The only use for this method is when you want to convert an object into an array:

$array = json_decode($request['object'], TRUE);

Why would you ever want to do that?

I mean, I do understand that there might be applications for this but on the other hand it took me a whole day to digest this way of thinking and it still feels like there's a huge mind gap.

This little convenience messes up with the concrete way of parsing data and is just confusing to a newbie like me.

like image 518
Vulkan Avatar asked May 24 '15 15:05

Vulkan


1 Answers

There's a clear distinction between arrays and objects in Javascript/JSON. Arrays do not have explicit indices but are numerically indexed, while objects are unsorted and have named properties. By default json_decode honours this difference and decodes JSON arrays to PHP arrays and JSON objects to PHP objects (instances of stdClass).

However, PHP's arrays also happen to support associative indices; so a JSON object could be decoded to either a PHP object or a PHP array. You can choose which you prefer with that second parameter to json_decode. There's no 100% clear 1:1 mapping between these two different languages here, so there's a preference instead.

like image 191
deceze Avatar answered Sep 29 '22 06:09

deceze