Home > Article > Backend Development > How to Remove a Single Variable from a PHP Session Array?
Removing a Specific Variable from a PHP Session Array
You're working with PHP code that manages variables in a user session. You can add variables to the session, but when you try to remove a specific variable using unset, all variables in the array are deleted. You need to find a way to remove only the intended variable.
To remove a specific variable from a PHP session array, you can use the following steps:
<code class="php">if (isset($_POST['remove'])) { $key = array_search($_GET['name'], $_SESSION['name']); if ($key !== false) unset($_SESSION['name'][$key]); $_SESSION["name"] = array_values($_SESSION["name"]); }</code>
Here's an example showcasing the usage:
<code class="php"><?php session_start(); // Add variables to session if (isset($_GET['name'])) { $name = isset($_SESSION['name']) ? $_SESSION['name'] : array(); $name[] = $_GET['name']; $_SESSION['name'] = $name; } // Remove a specific variable from session if (isset($_POST['remove'])) { $key = array_search($_GET['name'], $_SESSION['name']); if ($key !== false) unset($_SESSION['name'][$key]); $_SESSION["name"] = array_values($_SESSION["name"]); } // Print session data echo "<pre class="brush:php;toolbar:false">"; print_r($_SESSION); echo ""; ?>
In this example, the $list2 variable can be used to remove a specific variable from the session array by submitting the remove form.
The above is the detailed content of How to Remove a Single Variable from a PHP Session Array?. For more information, please follow other related articles on the PHP Chinese website!