Search code examples
phparraysreferencemultidimensional-arrayunset

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?


Solution

  • Ok, better answer I think. In order to unset , you should get a reference to the container array, then unset the element within the array;

    i.e.

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