Jump to content

Delete value from a mutidimensional array


Go to solution Solved by requinix,

Recommended Posts

Hi All,

 

I have been unsuccessfully trying to find a solution to delete a value from a multidimensional array. I found some tips here and there (e.g. http://stackoverflow.com/questions/4466159/delete-element-from-multidimensional-array-based-on-value), but was not able to adapt it to my case.

 

Basically, let say we have this initial print_r :

 

Array
(
    [v0] => Array
        (
            [w1] => Array
                (
                    [x2] => Array
                        (
                            [y3] => Array
                                (
                                    [0] => hello
                                    [1] => world
                                )
                        )
                )
        )
)

I want to find the value "world", and delete it so that the array looks like this :

 

Array
(
    [v0] => Array
        (
            [w1] => Array
                (
                    [x2] => Array
                        (
                            [y3] => Array
                                (
                                    [0] => hello
                                )
                        )
                )
        )
)

The data initially known are the array name and the value to look for.

Note that a given sub-array will contain only one sub-array or only one or more values.

 

Thanks for your help !

 

  • Solution

It's a lot simpler when you consider references.

// starting with $array and $value,

// go to the bottom of the array
for ($subarray =& $array; is_array(current($subarray)); $subarray =& $subarray[current(array_keys($subarray))]);
// that stuff with current+array_keys is because current() doesn't return by reference
// we need a reference so we don't unset() the value from the array *copy* we'd otherwise have

// find it in the values
$foundkey = array_search($value, $subarray);
if ($foundkey !== false) {
unset($subarray[$foundkey]);
}

// don't let the reference persist past this point
unset($subarray);
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.