phdphd Posted March 17, 2013 Share Posted March 17, 2013 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 ! Quote Link to comment https://forums.phpfreaks.com/topic/275760-delete-value-from-a-mutidimensional-array/ Share on other sites More sharing options...
Solution requinix Posted March 17, 2013 Solution Share Posted March 17, 2013 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); Quote Link to comment https://forums.phpfreaks.com/topic/275760-delete-value-from-a-mutidimensional-array/#findComment-1419105 Share on other sites More sharing options...
phdphd Posted March 17, 2013 Author Share Posted March 17, 2013 Thanks a lot Requinix. This is very, very impressive, at least for me ;-) Quote Link to comment https://forums.phpfreaks.com/topic/275760-delete-value-from-a-mutidimensional-array/#findComment-1419106 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.