Reputation: 365
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??
Upvotes: 1
Views: 357
Reputation: 101
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!
Upvotes: 0
Reputation:
@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']);
Upvotes: 0
Reputation: 3549
$key = array_search( 'token3', $_SESSION['tokens'] );
unset( $_SESSION['tokens'][$key] );
Upvotes: 7