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

Asked

Viewed 125 times

2

Sometimes I noticed that Docs suggests that instead of using the native method \json_encode() from PHP, he suggests using a class method for requests that apparently does the same thing \GuzzleHttp\json_encode(), but giving a read 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 had never entered any parameters in json_encode(), the doubt is the question title:

  • What the Depth parameter does when encoding a string ?

1 answer

4


It simply limits the maximum depth that will be processed.

This one, is a depth array 1:

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

This, is a depth array 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 depth greater than 512 (standard method), has high chances of being infinite

  • So reporting 512 (which is usually what I’m seeing) is totally unnecessary ?

  • 1

    It has its usefulness, you may want to explicitly limit the recursion limit for some reason

Browser other questions tagged

You are not signed in. Login or sign up in order to post.