0

The array is multi-dimensional and has a variable number of sub-keys, like

$arr[$a][$b][$c] = 'X';

3 in this case. I want to create a function that takes a string like a.b.c as argument and checks if the array has that key in it, then unset it: unset($arr[$a][$b][$c]).

if I give it a.b then it should unset($arr[$a][$b])

I'd appreciate any help...

0

1 Answer 1

2

Here is a recursive approach to your problem:

function removeByStr($key, &$arr)
{
    if(!is_array($key))
    {
        $key = explode(".", $key);
    }
    $i = array_shift($key);
    if(count($key) == 0)
    {
        if(!isset($arr[$i]))
        {
            return;
        }
        unset($arr[$i]);
    }
    else if(isset($arr[$i]) && is_array($arr[$i]))
    {
        removeByStr($key, $arr[$i]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

If there is $table[1][2][3], with a 1.2.4 key, your function will remove $table[1][2] while $table[1][2][4] doesn't exist.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.