Jonob Posted March 1, 2010 Share Posted March 1, 2010 I have a multi-dimensional array. Lets assume its something like: [0] [0] -> 'Green' [1] -> 'Soccer' [2] -> 'Oranges' [1] [0] -> 'Blue' [1] -> 'Rugby' [2] -> 'Apples' I want to remove the [2] index frome each sub-array, so that I land up with: [0] [0] -> 'Green' [1] -> 'Soccer' [1] [0] -> 'Blue' [1] -> 'Rugby' I can do this easily by looping through ...but is there an easier/faster way? Link to comment https://forums.phpfreaks.com/topic/193820-remove-subarray/ Share on other sites More sharing options...
aebstract Posted March 1, 2010 Share Posted March 1, 2010 Easier/faster way than? Where's the code that you're questioning? Link to comment https://forums.phpfreaks.com/topic/193820-remove-subarray/#findComment-1020106 Share on other sites More sharing options...
JAY6390 Posted March 1, 2010 Share Posted March 1, 2010 Not as far as I'm aware. Simplest way I can think of is a foreach foreach($array as &$v) { unset($v[2]); } Link to comment https://forums.phpfreaks.com/topic/193820-remove-subarray/#findComment-1020107 Share on other sites More sharing options...
Psycho Posted March 1, 2010 Share Posted March 1, 2010 Yes, there is a much easier method: array_diff_key() Using your example above: //Create an array with idexes of those to be removed $arrayKeysToRemove = array('2' => ''); $newArray = array_diff_key($originalArray, $arrayKeysToRemove); Link to comment https://forums.phpfreaks.com/topic/193820-remove-subarray/#findComment-1020117 Share on other sites More sharing options...
teamatomic Posted March 2, 2010 Share Posted March 2, 2010 array_diff_key wont work like that. You would need to build an array exactly the opposite of what you want then diff it against the original array. ie array( array(2=>'') array(2=>'') etc for each sub array The fastest and easiest way is the foreach you have been previously shown. HTH Teamatomic Link to comment https://forums.phpfreaks.com/topic/193820-remove-subarray/#findComment-1020249 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.