2

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));
Community
  • 1
  • 1
Detention
  • 167
  • 1
  • 1
  • 10

5 Answers5

2

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

mamdouh alramadan
  • 8,349
  • 6
  • 36
  • 53
2

How about:

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

And here's the proof of concept.

geomagas
  • 3,230
  • 1
  • 17
  • 27
  • Shouldn't "*// remove keys 0 and 1*" be "*// remove anything but keys 0 and 1*"? – h2ooooooo Oct 27 '13 at 09:43
  • @h2ooooooo: You're right, it's just a typo in the fiddle... sorry! Works, nevertheless. – geomagas Oct 27 '13 at 09:46
  • @mamdouhalramadan: Nah, merely fixed the last piece of code from the OP's question... There are other things I'm a lot more proud of ;) Cheers! – geomagas Oct 27 '13 at 10:24
0

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
);
Lix
  • 47,311
  • 12
  • 103
  • 131
0

You can even use array_splice()

$_SESSION['A']=array_splice($_SESSION['A'], 2);
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • Again, a nice idea... but what if the indexes are not sequential? `$_SESSION["A"][4]` and `$_SESSION["A"][2]`? – Lix Oct 27 '13 at 09:14
-3

try this

$_SESSION['A'] = array();
unset($_SESSION['A']);
Ankit Agrawal
  • 6,034
  • 6
  • 25
  • 49
  • Yea - but what does it do? It destroys the entire array. This is not what the question was asking for at all... – Lix Oct 27 '13 at 09:33