Home > Archive > 2010 > December

Algorithmic Advent: 03 – Addressing a multi-dimensional array index by string

By Marc Ermshaus on Friday, December 3, 2010 at 9:05 pm.

This function might come in handy when loading settings from a configuration file.

/**
 * Sets a field of a multi-dimensional array by specifying the key in a
 * flat string format
 *
 * Usage example:
 *
 *   $demo = array();
 *   arraySetByFlatKey($demo, 'this.is.a.test', 'Hello World!');
 *   arraySetByFlatKey($demo, 'this.is.a.monster', 'Brwaaa!');
 *
 * Sets:
 *
 *   $demo['this']['is']['a']['test'] = 'Hello World!';
 *   $demo['this']['is']['a']['monster'] = 'Brwaaa!';
 *
 * @param array $a Array to set the index of
 * @param string $key Flat key representation
 * @param mixed $value Value to set the index to
 */
function arraySetByFlatKey(array &$a, $key, $value, $delimiter = '.')
{
    $keyParts = explode($delimiter, $key);
    $leaveKey = array_pop($keyParts);

    $parent = &$a;

    foreach ($keyParts as $part) {
        if (!isset($parent[$part])) {
            $parent[$part] = array();
        }

        $parent = &$parent[$part];
    }

    $parent[$leaveKey] = $value;
}

Add new comment

Name*:

Please leave the following field empty:

E-Mail:

Website:

Message*:

Please use HTML for formatting. Allowed tags:
<a href="">, <blockquote cite="">, <em>, <ul>, <ol>, <li>, <pre>, <strong>, <![CDATA[ … ]]>

<p> tags will be added automatically.

All comments are published under the CC BY-SA license.