PHP: unset $_SESSION of array

259 Views Asked by At

I have a session of arrays named:

$_SESSION['A'];

it contains

$_SESSION['A'][0] = 'A';
$_SESSION['A'][1] = 'B';

I can unset the $_SESSION['A']; using

unset($_SESSION['A']);

it unset all the value in the array how can I unset all value stored in

$_SESSION['A']; 

exept

$_SESSION['A'][0];
$_SESSION['A'][1];

I've seen this POST

which it unset all $_SESSION exept some stored in array. I used this code to unset it on array but I don't know how to used it as arrays.

$keys = array('x', 'y');
$_SESSION = array_intersect_key($_SESSION, array_flip($keys));
5

There are 5 best solutions below

3
mamdouh alramadan On BEST ANSWER

use array_slice like this:

$_SESSION['A'] = array_slice($_SESSION['A'], 0, 2);

Update:

Also, for non sequential indexes we can create this function:

  function array_pick($picks, $array)
    {
     $temp = array();
        foreach($array as $key => $value)
        {
            if(in_array($key, $picks))
            {
                $temp[$key] = $value;
            }
        }
     return array_values($temp);// or just $temp to keep original indexes
    }

PHPFiddle

0
Lix On

You won't be able to do unset only certain values in an array. Rather, just save the values of those variables, unset the entire array and then reset the values.

// Save existing values
$saved_var1 = $_SESSION["A"][0];
$saved_var2 = $_SESSION["A"][1];

// Unset the entire array
unset( $_SESSION["A"] );

// Set the values by the saved variables
$_SESSION["A"] = array(
  $saved_var1,
  $saved_var2
);
1
Ankit Agrawal On

try this

$_SESSION['A'] = array();
unset($_SESSION['A']);
1
Shankar Narayana Damodaran On

You can even use array_splice()

$_SESSION['A']=array_splice($_SESSION['A'], 2);
3
geomagas On

How about:

$keys = array(0,1);
$_SESSION['A'] = array_intersect_key($_SESSION['A'], array_flip($keys));

And here's the proof of concept.