Home

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

Published on 3 Dec 2010. Tagged with php, algorithmicadvent.

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;
}