Multidimensional array unset

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Darkzaelus
Forum Commoner
Posts: 94
Joined: Tue Sep 09, 2008 7:02 am

Multidimensional array unset

Post 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
Darkzaelus
Forum Commoner
Posts: 94
Joined: Tue Sep 09, 2008 7:02 am

Re: Multidimensional array unset

Post 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
Post Reply