Search code examples
phpmigrationphp-7.2jsondecoder

Migrating from PHP 7.1.x to PHP 7.2.x json_decode() change


The official doc says:

The json_decode() function option, JSON_OBJECT_AS_ARRAY, is now used if the second parameter (assoc) is NULL. Previously, JSON_OBJECT_AS_ARRAY was always ignored.

This code (AFAIK) accomplishes this change and condition :

<?php

$an_object = new StdClass();
$an_object->some_atrribute = "value 1";
$an_object->other_atrribute = "value 2";

//an object
print_r($an_object);

$encoded = json_encode($an_object);

//here (null is passed in the second parameter)
$output = json_decode($encoded,null,512);

//using 7.2 should be array, however it is an object
print_r($output);

//array
$output = json_decode($encoded,true);
print_r($output);

However only the last print, prints as array.

Am I understanding something wrong?


Solution

  • Check the function signature:

    mixed json_decode ( string $json [, bool $assoc = FALSE 
      [, int $depth = 512 [, int $options = 0 ]]] )
    

    options

    Bitmask of JSON decode options. Currently there are two supported options. The first is JSON_BIGINT_AS_STRING that allows casting big integers to string instead of floats which is the default. The second option is JSON_OBJECT_AS_ARRAY that has the same effect as setting assoc to TRUE.

    It means you can set the fourth parameter to JSON_OBJECT_AS_ARRAY even if you didn't set the second parameter to true for some reason, but set it to null instead. But default value of this fourth param is 0, which means no transformation (from object to array) if only second param is set to null.

    Here's the shortened demo showing the difference:

    $an_object = new StdClass();
    $an_object->attr = 'value';
    
    $encoded = json_encode($an_object);
    print_r( json_decode($encoded, true, 512, JSON_OBJECT_AS_ARRAY)  );
    print_r( json_decode($encoded, false, 512, JSON_OBJECT_AS_ARRAY) );
    print_r( json_decode($encoded, null, 512, JSON_OBJECT_AS_ARRAY)  );
    

    Here you'll see array and object printed as result of first and second decode ops in all the PHP versions. But the third op will result in array only since PHP 7.2.0.