Check if a “run-time” multidimensional array key exists
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/6080991/check-if-a-run-time-multidimensional-array-key-exists">Check if a &ldquo;run-time&rdquo; multidimensional array key exists</a>  </p>
</blockquote>



<p>Hi,</p>

<p>I have a multidimensional array. I need a function that checks if a specified key exists and if not set the value.</p>

<p>Let's take this array</p>

<pre><code>$config['lib']['template']['engine'] = false;
</code></pre>

<p>A function should not update the value to true when i call with:</p>

<pre><code>checkAndSetKey('lib template engine',true);
//&gt; Checks if isset $config['lib']['template']['engine'] and if not isset $config['lib']['template']['engine'] = true;
</code></pre>

<p>Note that my array isn't only 3 dimensional. It should be able to check and set even with only 1 dimension:</p>

<pre><code>checkAndSetKey('genericSetting',true);
//&gt; In this considering there isn't any $c['genericSetting'] the function set the key to true;
</code></pre>

<p>At the moment I am using an awful eval code, I would like to hear suggest :)</p>

<p>To dynamically check if the key exists it could be used this code:</p>

<pre><code>$array = $config;
$keys=explode(' ',$argument1);

foreach($keys as $v) { 

    if (!array_key_exists($v,$array)) {
        //&gt; [todo!] the current key doens't exist now we should set the value
    }

    $array = &amp;$array[$v];
}
</code></pre>
