tibberous Posted July 14, 2008 Share Posted July 14, 2008 If I have an array, $arr = array('red', 'green', 'blue'), how can I delete green? Link to comment https://forums.phpfreaks.com/topic/114596-delete-element-from-array-by-value/ Share on other sites More sharing options...
unsider Posted July 14, 2008 Share Posted July 14, 2008 You can use unset() to remove array elements. For indexed arrays PHP does not reorder the index after an unset(), so you can end up with non-sequential indices. unset($arr[1]); Although it's possible I'm wrong, but atleast it gives you a search term for google Link to comment https://forums.phpfreaks.com/topic/114596-delete-element-from-array-by-value/#findComment-589212 Share on other sites More sharing options...
tibberous Posted July 14, 2008 Author Share Posted July 14, 2008 Right - but green is the value, not the key. Link to comment https://forums.phpfreaks.com/topic/114596-delete-element-from-array-by-value/#findComment-589296 Share on other sites More sharing options...
.josh Posted July 14, 2008 Share Posted July 14, 2008 $arr = array('red', 'green', 'blue'); foreach ($arr as $key => $val) { if ($val == "green") { unset($arr[$key]); } } Link to comment https://forums.phpfreaks.com/topic/114596-delete-element-from-array-by-value/#findComment-589299 Share on other sites More sharing options...
Barand Posted July 14, 2008 Share Posted July 14, 2008 or unset ($array[array_search('green', $array)]); Link to comment https://forums.phpfreaks.com/topic/114596-delete-element-from-array-by-value/#findComment-589317 Share on other sites More sharing options...
tibberous Posted July 17, 2008 Author Share Posted July 17, 2008 or unset ($array[array_search('green', $array)]); Neat. Seems like their should be a built in function, but that's still neat. Link to comment https://forums.phpfreaks.com/topic/114596-delete-element-from-array-by-value/#findComment-592459 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.