Page 1 of 1

Multidimensional array unset

Posted: Mon Nov 23, 2009 12:57 pm
by Darkzaelus
Hiya,

Is it at all possible to take a string like 'test.test2.test3', turn it into a reference and unset that index?

I've been trying to do it with pointers, and i've avoiding eval()'ling the code (This is for a templating engine, trying to get rid of persistance indexes outside of closures).

The code I have at the moment is:

Code: Select all

if(strpos($key, '.')) {
    $found=true;
    $parts=explode('.', $key);
    $pointer=&$this->_vars[array_shift($parts)];
    foreach($parts as $part)
        if(isset($pointer[$part]))
            $pointer=&$pointer[$part];
        else break;
    if($found) {
        unset($pointer);
    }
} else unset($this->_vars[$key]);
If there were a way to do this I would be grateful!

Cheers,

Darkzaleus

Re: Multidimensional array unset

Posted: Mon Nov 23, 2009 2:05 pm
by Darkzaelus
Right! I figured it out using code from Stack Overflow:

Code: Select all

if(strpos($key, '.')) {
    $found=true;
    $parts=explode('.', $key);
    $this->unasign($this->_vars, $parts);
} else unset($this->_vars[$key]);

Code: Select all

private function unasign(&$array, $complexKey) {
    if(sizeof($complexKey)==1&&isset($array[$complexKey[0]]))
        unset($array[$complexKey[0]]);
    else {
        $shift=array_shift($complexKey);
        foreach($array as $key=>&$value) {
            if($shift==$key&&is_array($value))
                $this->unasign($value, $complexKey);
        }
    }
}
Edit: Added the check for key so it won't go down array paths that are not related.

Hope this helps people!

Cheers,

Darkzaelus