LiveEn LiveEn - 3 months ago 18
PHP Question

How to remove a variable from a PHP session array

I have PHP code that is used to add variables to a session:

<?php
session_start();
if(isset($_GET['name']))
{
$name = isset($_SESSION['name']) ? $_SESSION['name'] : array();
$name[] = $_GET['name'];
$_SESSION['name'] = $name;
}
if (isset($_POST['remove']))
{
unset($_SESSION['name']);
}
?>
<pre> <?php print_r($_SESSION); ?> </pre>

<form name="input" action="index.php?name=<?php echo $list ?>" method="post">
<input type="submit" name ="add"value="Add" />
</form>

<form name="input" action="index.php?name=<?php echo $list2 ?>" method="post">
<input type="submit" name="remove" value="Remove" />
</form>


I want to remove the variable that is shown in
$list2
from the session array when the user chooses 'Remove'.

But when I unset, ALL the variables in the array are deleted.

How I can delete just one variable?

Answer
if (isset($_POST['remove'])) {
    $key=array_search($_GET['name'],$_SESSION['name']);
    if($key!==false)
    unset($_SESSION['name'][$key]);
    $_SESSION["name"] = array_values($_SESSION["name"]);
} 

Since $_SESSION['name'] is an array, you need to find the array key that points at the name value you're interested in. The last line rearranges the index of the array for the next use.