Jump to content

Unset from array not working

Recommended Posts

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: 




Can you only unset the keys? of the array like 0 1 2? 

Share this post

Link to post
Share on other sites

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:



Of course, you'll want to make sure there are no duplicate values in the array before using array_flip().

  • Like 1

Share this post

Link to post
Share on other sites


$arr = [5,3,2];              // orig array
$rem = [3,2];                // array of items to be removed
$arr = array_diff($arr,$rem);

Share this post

Link to post
Share on other sites

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) {
Edited by CroNiX

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.