How to remove a variable from a PHP session array

To remove a variable from a PHP session array, you can use the unset() function. Here's an example:

<?php

// Start the session
session_start();

// Remove a variable from the session array
unset($_SESSION['var_name']);

This will remove the variable 'var_name' from the session array. If you want to remove multiple variables, you can pass them as additional arguments to unset(), like this:

<?php

unset($_SESSION['var_name1'], $_SESSION['var_name2'], $_SESSION['var_name3']);

Watch a course Learn object oriented PHP

Alternatively, you can use the array_splice() function to remove an element from the session array by its index:

<?php

// Remove the element at index 1 from the session array
array_splice($_SESSION, 1, 1);

Keep in mind that this will change the indexes of the remaining elements in the array. If you want to remove an element by its value, you can use the array_search() function to find its index and then use array_splice() to remove it:

<?php

$key = array_search('value', $_SESSION);
if ($key !== false) {
  array_splice($_SESSION, $key, 1);
}