Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unset a element of an array via reference

I can access anywhere inside the multi-dimensional an array via reference method. And I can change the its value. For example:

$conf = array(
    'type' => 'mysql',
    'conf' => array(
            'name' => 'mydatabase',
            'user' => 'root',
            'pass' => '12345',
            'host' => array(
                    '127.0.0.1',
                    '88.67.45.123',
                    '129.34.123.55'
            ),
            'port' => '3306'
    )
);

$value = & $this->getFromArray('type.conf.host');
$value = '-- changed ---';

// result
$conf = array(
    'type' => 'mysql',
    'conf' => array(
            'name' => 'mydatabase',
            'user' => 'root',
            'pass' => '12345',
            'host' => '-- changed ---'
            'port' => '3306'
    )
);

BUT, I can't destroy the that section:

// normally success
unset($conf['type']['conf']['host']);

// fail via reference
$value = & $this->getFromArray('type.conf.host');
unset($value);

Is there a solution?

like image 264
eburhan Avatar asked Sep 07 '10 20:09

eburhan


1 Answers

Here is my function for unsetting nested keys

public function unsetKey(string $dotSeparatedKey)
{
    $keys = explode('.', $dotSeparatedKey);
    $pointer = &$this->data;
    $current = false; // just to make code sniffer happy
    // we traverse all but the last key
    while (($current = array_shift($keys)) && (count($keys) > 0)) {
        // if some key is missing all the subkeys will be already unset
        if (!array_key_exists($current, $pointer)) {
            // is already unset somewhere along the way
            return;
        }
        // set pointer to new, deeper level
        // called for all but last key
        $pointer = &$pointer[$current];
    }
    // handles empty input string
    if ($current) {
        // we finally unset what we wanted
        unset($pointer[$current]);
    }
}
like image 163
Tomáš Fejfar Avatar answered Sep 21 '22 12:09

Tomáš Fejfar