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 ! Link to comment https://forums.phpfreaks.com/topic/275760-delete-value-from-a-mutidimensional-array/ Share on other sites More sharing options...
requinix Posted March 17, 2013 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); 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 ;-) 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
Archived
This topic is now archived and is closed to further replies.