What is the purpose of using depth in JSON encode?

json, php

Solution

The option limits the depth that will be processed (d'uh). The depth of an array is measured by how deep it is nested. 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'
    )
)

// ------ depth ------>

If the input surpasses the maximum depth (by default 512), `json_encode` will simply return `false`.

Why you may use this is debatable, you may want to protect yourself from inadvertent infinite recursion or too much resource use. An array which is deeper than 512 levels probably has infinitely recursive references and cannot be serialised. But if you are sure your array is not infinitely recursive yet is deeper than 512, you may want to increase this limit explicitly. You may also want to lower the limit as a simple error catcher; say you expect the result to have a maximum depth but your input data may be somewhat unpredictable.

Problem

I have this example code: ``` $array = array( 'GiamPy' => array( 'Age' => '18', 'Password' => array( 'password' => '1234', 'salt' => 'abcd', 'hash' => 'whirlpool' ), 'Something' => 'Else' ) ); echo json_encode($array, JSON_PRETTY_PRINT); ``` I have seen in the PHP documentation that, since PHP 5.5.0 (thus recently), `json_encode` allows a new parameter which is the depth. - What is its purpose? - Why would I ever need it? - Why has it been added in PHP 5.5.0?

Original source