Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I see you have excepted an answer, but here's an alternative:</p> <pre><code>&lt;?php $arrayHandler = new ArrayHandler(); $arr = array(); //Adding array examples (without checking) $arr[0]['subcategories'] = array('id'=&gt;80); $arr[0]['subcategories']['whatever'] = array('id'=&gt;82); $arr[0]['subcategories']['whatever']['whatever2'] = array('id'=&gt;83); //Will be added because this is fourth level from $arr[0] $chk = $arrayHandler-&gt;addSubArray($arr[0], $arr[0]['subcategories']['whatever']['whatever2']['whatever3']); if ($chk !== false) { $arr[0]['subcategories']['whatever']['whatever2']['whatever3'] = array('id'=&gt;84); } //Won't be added because this is fitfth level from $arr[0] $chk = $arrayHandler-&gt;addSubArray($arr[0], $arr[0]['subcategories']['whatever']['whatever2']['whatever3']['whatever4']); if ($chk !== false) { $arr[0]['subcategories']['whatever']['whatever2']['whatever3']['whatever4'] = array('id'=&gt;85); } echo print_r($arr,true); class ArrayHandler { private $depthLimit = 4; private $depth = 1; public function addSubArray($checkFromNode, $addNode) { if (is_array($checkFromNode)) { //Do recursion as long as node is an array and count depth //If not an array anymore return value sent to this parameter foreach ($checkFromNode as $key=&gt;$node) { if (is_array($node)) { $this-&gt;depth++; $this-&gt;addSubArray($node, $addNode); } } if (intval($this-&gt;depth) &gt; intval($this-&gt;depthLimit)) { return false; } return true; } } } ?&gt; </code></pre> <p>Output would be in example:</p> <pre><code>Array ( [0] =&gt; Array ( [subcategories] =&gt; Array ( [id] =&gt; 80 [whatever] =&gt; Array ( [id] =&gt; 82 [whatever2] =&gt; Array ( [id] =&gt; 83 [whatever3] =&gt; Array ( [id] =&gt; 84 ) ) ) ) ) ) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload