views:

111

answers:

2

Hi,

Question related to PHP memory-handling from someone not yet very experienced in PHP:

If I set a PHP session variable of a particular name, and then set a session variable of the exact same name elsewhere (during the same session), is the original variable over-written, or does junk accumulate in the session?

In other words, should I be destroying a previous session variable before creating a new one of the same name?

Thank you.

+2  A: 

$_SESSION works just like any other array, so if you use the same key each time, the value is overwritten.

Matti Virkkunen
+1  A: 

Tom,

It depends on how you use the session variable, but it generally means "erasing" that variable (replacing the old value by the new value, to be exact).

A session variable can store a string, a number or even an object.


<?php
    # file1.php
    session_start();
    $_SESSION['favcolor'] = 'green';
    $_SESSION['favfood'] = array('sushi', 'sashimi');
?>

After this, the $_SESSION['favcolor'] variable and the $_SESSION['favfood'] variable is stored on the server side (as a file by default). If the same user visit another page, the page can get the data out from, or write to the same storage, thus giving the user an illusion that the server "remembers" him/her.


<?php
    # file2.php
    session_start();
    echo $_SESSION['favcolor'], '<br />';
    foreach ($_SESSION['favfood'] as $value) {
        echo $value, '<br />';
    }
?>

Of course, you may modify the $_SESSION variable in the way you want: you may unset() any variable, append the array in the example by $_SESSION['favfood'][] = 'hamburger'; and so on. It will all be stored to the session file (a file by default, but could be a database). But please beware that the $_SESSION variable acts magically only after a call to session_start(). That means in general, if you use sessions, you have to call session_start() at the beginning of every page of your site. Otherwise, $_SESSION is just a normal variable and no magic happens :-).

Please see the PHP reference here for more information.

Siu Ching Pong - Asuka Kenji
Thanks very much for the extra information.
Tom