blmg2009 Posted August 18, 2015 Share Posted August 18, 2015 I have the following array: Array ( [0] => 5 [1] => 3 [2] => 2 ) I'm wanting to remove the 5 and 3 from the array but the following isn't working: unset($list['5']); Can you only unset the keys? of the array like 0 1 2? Quote Link to comment https://forums.phpfreaks.com/topic/297854-unset-from-array-not-working/ Share on other sites More sharing options...
cyberRobot Posted August 18, 2015 Share Posted August 18, 2015 The "5" in your unset() example needs to refer to a key...assuming that $list is your array. You could use a foreach loop to get the array index for the items you want to remove and then use unset(). Note that you could also consider using array_flip() to swap the array's keys and values; unset the items you want to remove; and then flip the array back. More information about array_flip() can be found here: http://php.net/manual/en/function.array-flip.php Of course, you'll want to make sure there are no duplicate values in the array before using array_flip(). 1 Quote Link to comment https://forums.phpfreaks.com/topic/297854-unset-from-array-not-working/#findComment-1519212 Share on other sites More sharing options...
blmg2009 Posted August 18, 2015 Author Share Posted August 18, 2015 Thank you I will look into these options now. Quote Link to comment https://forums.phpfreaks.com/topic/297854-unset-from-array-not-working/#findComment-1519213 Share on other sites More sharing options...
Barand Posted August 18, 2015 Share Posted August 18, 2015 or $arr = [5,3,2]; // orig array $rem = [3,2]; // array of items to be removed $arr = array_diff($arr,$rem); Quote Link to comment https://forums.phpfreaks.com/topic/297854-unset-from-array-not-working/#findComment-1519214 Share on other sites More sharing options...
CroNiX Posted August 19, 2015 Share Posted August 19, 2015 (edited) You can also use array_search() to look for a value in the array and if it exists it will return the associated key (or FALSE if not). You can then use the key to unset the index from the array. if (($key = array_search($value_to_delete, $your_array)) !== false) { unset($your_array[$key]); } Edited August 19, 2015 by CroNiX Quote Link to comment https://forums.phpfreaks.com/topic/297854-unset-from-array-not-working/#findComment-1519256 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.