What does the depth parameter of the json_encode () method mean?

2

Sometimes I noticed that docs suggests that instead of using the \json_encode() native method of PHP, it suggests using a method of a class for requests that apparently does the same thing \GuzzleHttp\json_encode() , but giving a handle in the files of this class I found the following method:

function json_encode($value, $options = 0, $depth = 512)
{
    $json = \json_encode($value, $options, $depth);
    if (JSON_ERROR_NONE !== json_last_error()) {
        throw new \InvalidArgumentException(
            'json_encode error: ' . json_last_error_msg());
    }

    return $json;
}

I've never entered any parameters in json_encode (), doubt is the title of the question:

  • What does the depth parameter do when encoding a string?
asked by anonymous 07.11.2017 / 13:37

1 answer

4

It simply limits the maximum depth that will be processed.

This is an array of depth 1:

array(
    'foo',
    'bar',
    'baz'
)

This is an array of depth 2:

array(
    array(
        'foo'
    ),
    array(
        'bar'
    ),
    array(
        'baz'
    )
)

If the input depth is greater than $depth , the method will simply return false

You may want to use this parameter to avoid too much processing. An array with a depth greater than 512 (method pattern) has great chances of being infinite

    
07.11.2017 / 13:40