4

I have some arrays that I'd like to unset based on a key.

For example, let's say I have this array:

$array = array(
  'one' => array('item' => '1'),
  'two' => array('item' => '2')
);

If I want to unset the nested array with key 'two', I could do:

unset($array['two'])

or if I wanted to unset just the item array for key 'two', I could do:

unset($array['two']['item'])

I want to dynamically delete array items based on known keys. So for example, I know I want to delete ['two']['item'].

How do I pass those two arguments to a method, that can then be appended to an array?

Example:

//This works fine if it's only the first item in the array
function deleteArray($keys)
{
  unset($this->array[$keys]);
}

But when we want to delete nested items, this would not work. I could pass in the keys as an array such as array('two', 'item') and build the index off of this, but not sure how....

Any help would be great! thank you!

3 Answers 3

6

You can use this function:

function delete(&$array, $keys)
{
   $key = array_shift($keys);

   if (count($keys) == 0)
      unset($array[$key]);
   else
      delete($array[$key], $keys);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try with a recursive function:

function deleteArray(&$array, $keys) {
    if ( count($keys) == 1 )
       unset( $array[$keys[0]] );
    else
    {
       $k = array_shift($keys);
       deleteArray($array[$k],$keys); 
    }
}
deleteArray($this->arr, array("three","item","blabla")); // This erase $this->array["three"]["item"]["blabla"]

Comments

0
function deleteArray($keys)
{
$keyarray = explode($keys, " ");
   unset($this->array[$keyarray[0]][$keyarray[1]]);
}

I edited it a bit (won't work!) maybe somebody could continue that. Maybe it is possible with a while() ...

2 Comments

What if there are 10 arguments? Ideally, the number of arguments would be dynamic.
Well no, sry I don't know if that's possible.

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.