Jump to content

Delete value from a mutidimensional array


phdphd

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 !

 

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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.