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? Quote 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 Quote 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. Quote 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]); } } Quote 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)]); Quote 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. Quote 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
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.