MattD
MattD

Reputation: 179

PHP - Add to multidimensional array if key doesn't exist

Having a hard time figuring out how to explain it, so maybe the code will help.

$out = array();

source_addValue($out['sources']['site1']['user_id'], '12345');
source_addValue($out['sources']['site1']['username'], 'testuser');
source_addValue($out['sources']['site1']['address']['state'], 'CA');

function source_addValue($field, $value) {
    global $out;
    if (!$field) $field = $value;
}

That, or since the $out['sources'] part remain the same, maybe something like:

$out = array();

source_addValue('site1', 'user_id', '12345');
source_addValue('site1', 'username', 'testuser');
source_addValue('site1', array('address','state'), 'CA');

function source_addValue($site, $field, $value) {
    global $out;
    if (!$out['sources'][$site]$field) $out['sources'][$site]$field = $value;
}

Either way, I'm getting hung up on the function, and specifically the if statement. I just need to be able to check to see if that array value has been set for $out (with the ability to check sub-arrays) and if it isn't, add it to the $out array.

Upvotes: 0

Views: 1726

Answers (2)

Lloyd Banks
Lloyd Banks

Reputation: 36648

Rambo's function doesn't check whether the current key has been set or not. It overwrites all keys that already have a value. Here's a modified version that checks for keys already present

$out = array();

source_addValue(array('sources', 'site1', 'user_id'), '12345');
source_addValue(array('sources', 'site1', 'username'), 'testuser');
source_addValue(array('sources', 'site1', 'address', 'state'), 'CA');

function source_addValue($pathKeys, $val) {
    global $out;
    foreach ($pathKeys as $key) {
        if (!isset($out[$key]) && !is_array($out[$key])) {
            $out[$key] = array();
        }
        $out =& $out[$key];
    }
    if(empty($out)){
        $out = $val;
    }
}

print_r($out);

Upvotes: 0

goat
goat

Reputation: 31813

I'm not confident I understand what you wan't, but I'll guess:

function autoVivifyDynamicKeyPath($pathKeys, $val) {
    global $out;
    $cursor =& $out;
    foreach ($pathKeys as $key) {
        if (!isset($cursor[$key]) || !is_array($cursor[$key])) {
            $cursor[$key] = array();
        }
        $cursor =& $cursor[$key];
    }
    $cursor = $val;
}
autoVivifyDynamicKeyPath(array('site1', 'address', 'state'), 'ca');

Upvotes: 2

Related Questions