3

is there any difference between json_decode($var) and (object)json_decode($var, true)?

While recently working at certain piece of code in Joomla virtuemart, I came to a puzzled situation. Virtumart uses (object)json_decode($var, true) for its cartObject, and if I change it to simple json_decode($var), it shows some error afterwards. On further debugging I found the cart structure as:

stdClass Object
(
    [cartProductsData] => Array
        (
        )
    [vendorId] => 0
    [automaticSelectedShipment] => 
    [automaticSelectedPayment] => 
    [order_number] => 
    [BT] => Array
        (
        )
    [ST] => Array
        (
        )
)

Though on changing code, i.e, json_decode($var), the result is:

stdClass Object
(
    [cartProductsData] => Array
        (
        )
    [vendorId] => 0
    [automaticSelectedShipment] => 
    [automaticSelectedPayment] => 
    [order_number] => 
    [BT] => stdClass Object
        (
        )
    [ST] => stdClass Object
        (
        )
)

So BT and ST are objects now,rather than arrays as earlier they are, but how? Any explanation would be appreciated.

Anant
  • 534
  • 11
  • 40

2 Answers2

3

This is because, of json_decode() return type

In json_decode($var), it returns the whole json data as object, including inner components. (All levels)

But, json_decode($var, true) returns whole json data in array structure, including inner components. (All levels)

So, when (object)json_decode($var, true) is used, json_data returns data as array and only the outermost or main array (1st level) gets casted into object.

Robin Panta
  • 224
  • 3
  • 11
-1

This is because php treat empty array as empty list in json.

$a = json_encode([]);
$b = json_decode($a);
$c = (object)json_decode($a, true);
var_dump($b, $c);

you can find that $b is an array, but $c is an object. in your case, value of BT and ST is empty array/list, so you have different result.

Joey
  • 1,233
  • 3
  • 11
  • 18