phpunsetstdclass

PHP Removing by reference


I'm trying to remove stdClass property by reference. Because I don't know how deeply the property is nested, a reference is made in the loop. But the unset method does not remove variables by reference. How can I resolve it without just setting a null value?

<?php
$data = new stdClass();
$data->foo = new stdClass();
$data->foo->bar = 'value';

$pathToRemove = 'foo.bar';

$dataReference = &$data;
foreach (explode('.', $pathToRemove) as $field) {
    $dataReference = &$dataReference->$field;
}
unset($dataReference);

var_dump($data);

Solution

  • Loop over all the elements except the last. Then use the last element as the field to delete.

    $pathArray = explode('.', $pathToRemove);
    $lastField = array_pop($pathArray);
    $dataReference = &$data;
    foreach ($pathArray as $field) {
        $dataReference = &$dataReference->{$field};
    }
    unset($dataReference->{$lastField});
    unset($dataReference); // don't need the reference variable any more