0

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

7
  • 2
    use the php unset() method for that Commented Jul 19, 2017 at 7:54
  • unset($translation_arr['fr']); will work. Commented Jul 19, 2017 at 7:56
  • try this, stackoverflow.com/questions/369602/… Commented Jul 19, 2017 at 7:57
  • @NanaPartykar yes but how build key ['fr'] from string ? Commented Jul 19, 2017 at 7:59
  • 1
    Paste your working code @NicolasLamblin Commented Jul 19, 2017 at 8:00

4 Answers 4

2

Try this

 unset(ArrayName[key][key].....)
Sign up to request clarification or add additional context in comments.

4 Comments

Yes but how build key [key][key] from string ?
$keys = explode('.',"translations.fr") ; $keys[0] = translations; $keys[1] = fr; in this you can get keys
explode give an array with each key. My problem is to transform this array in $array[$key][$key]
try this $keys = explode('.',"translations.fr") ; $keys[0] -> translations; $keys[1] -> fr; ... unset(${$keys[0]}[$keys[1]]); // ${arrayname}[key]
0

Try this :

If you want to replace the same array and delete the "fr" completely

$translationArray = unset($translationArray['fr']);

If you want to retain the previous array and save the changes in a new one

$translationArrayNew = unset($translationArray['fr']);

Comments

0

I think this is what you're looking for:

$str = 'translations.fr';
$exploded = explode('.', $str);
$array = [
        'translations' => [
                'fr' => 'fr value',
                'es' => 'es value',
                ]
        ];

unset($array[$exploded[0]][$exploded[1]]);

With explode you put your string into an array containing 2 keys: 0 => translations 1 => fr

This accesses the 'translations' key within your array

$array[$exploded[0]]

and this accesses the 'fr' key within 'translations'

$array[$exploded[0]][$exploded[1]]

it's like writing: $array['translations]['fr']

Comments

0

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];
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.