Search code examples
phparraysunset

How delete array elements from string


I need to delete a key in an array from a string.

String is translations.fr

Array is

[
    ...,
    translations => [
          fr => [
              ...
          ],
          es => [
              ...
          ]
    ],
    ...,
]

Result must be :

[
    ...,
    translations => [
          es => [
              ...
          ]
    ],
    ...,
]

I think, using exlpode and unset is the good way.

Can you help me ? Thank's


Solution

  • Solution :

    public function deleteKeyV3($keyToDelete) {
        $keys = explode('.', $keyToDelete);
        $result = &$array;
    
        foreach ($keys as $key) {
            if (isset($result[$key])) {
                if ($key == end($keys)) {
                    unset($result[$key]);
                } else {
                    $result = &$result[$key];
                }
            }
        }
    }