0

I'm trying to remove an element in a multidimensional array.

The element which is needs to be removed is given by a string like globals.connects.setting1. This means I'm intend to modify an array like this:

// Old Array
$old = array(
    "globals" => array(
        "connects" => array(
            "setting1" => "some value",
            "setting2" => "some other value",
            "logging" => array()),
    "someOtherKey" => 1
));

// After modification
$new = array(
    "globals" => array(
        "connects" => array(
            "setting2" => "some other value",
            "logging" => array()),
    "someOtherKey" => 1
));

Unfortunately I do not know either the "depth" of the given string nor the exact structure of the array. I'm looking for a function like unsetElement($path, $array) which returns the array $new, if the array $old and globals.connects.setting1 is given as argument.

I'd like to avoid the use of the eval() function due to security reasons.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Ingo
  • 99
  • 6
  • 3
    Your code "example" is not valid PHP (and I'm not talking about the ellipsis). And this question, with valid code examples, has been answered several times on [so]. – axiac Feb 22 '18 at 15:34
  • Discussed on Meta https://meta.stackoverflow.com/questions/363695/mark-as-duplicate-of-old-answer-after-adding-to-old-answer-or-not so unfortunately there will be some drive-by downvoters to everything. – AbraCadaver Feb 22 '18 at 18:22
  • I'm sorry for the (stupid) question. In fact i was aware of the cited question (which this question is a duplicate of). But I had something in mind, that using unset in the context of references will remove the reference and not an element fo the referenced object. Obviously I was wrong. I'm sorry. Thanks a lot to everybody participating in the conversation. – Ingo Feb 23 '18 at 09:20

1 Answers1

-1
  $testArr = [
        "globals" => [
            "connects" => [
                'setting1' => [
                    'test' => 'testCon1',
                ],
                'setting2' => [
                    'abc' => 'testCon2',
                ],
            ],
        ],
        'someOtherKey' => [],
    ];

$pathToUnset = "globals.connects.setting2";

    function unsetByPath(&$array, $path) {
        $path = explode('.', $path);
        $temp = & $array;

        foreach($path as $key) {
            if(isset($temp[$key])){
                if(!($key == end($path))) $temp = &$temp[$key];
            } else {
               return false; //invalid path
            }
        }
        unset($temp[end($path)]);
    }

    unsetByPath($testArr, $pathToUnset);
vpalade
  • 1,427
  • 1
  • 16
  • 20