简体   繁体   中英

How to remove an element from an array stored in SESSION

I have an array

$tokens = array('token1','token2','token3','token4','token5','token6');

I have stored this array in SESSION

$_SESSION["tokens"] = $tokens;

Now, I need to remove an element from this array

  if(in_array('token3',$_SESSION["tokens"])) {

    // remove it from the array

  }

So, How can I remove 'token3' element from $_SESSION["tokens"] array??

$key = array_search( 'token3', $_SESSION['tokens'] );
unset( $_SESSION['tokens'][$key] );

@Andrey Volk's array_search took the job. But when you unset, you may need array_value to resort the key index of that array to avoid the discrete.

$_SESSION['tokens'] = array_values($_SESSION['tokens']);

There is a method called "unset()" in php which is used to unset the variables as the name says...

as you are using an array in the $_SESSION variable, you need to find the key of the element you want to delete...

to find the key, you simply search the array for a value. There is a method called array_search which takes 2 arguments, the first one is the element to search for and the second argument is the array in which you want to search. In this case using array search to search for 'token3' in the tokens array which is $_SESSION['tokens']:

$key = array_search( 'token3', $_SESSION['tokens'] );

okay, now we have the key of the element to delete, so lets delete the element using the unset method:

unset( $_SESSION['tokens'][$key] );

hope that helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM