Search code examples
phparraysreplacetemporal

Modifying an array value not working


I'm trying to change one piece of information in an array. Here is what I have: (set.php)

require_once('config.php');

$spotid = $_GET['id'];

$array = & $spotsopen;
//$opennot = $spotsopen[$spotid];

$spotsopen[$spotid] = false;

and the config.php has the spotsopen array:

    $spotsopen = array(
    '1' => true,
    '2' => true,
    '3' => true,
    '4' => false,
    '5' => false,
    '6' => true,
    '7' => true,
    '8' => true,
    '9' => true,
    '10' => true,
    '11' => true,
    '12' => true,
    '13' => true,
    '14' => true,
    '15' => true,
    '16' => true,
    '17' => true,
    '18' => true,
    '19' => true
);

So I have a page, that redirects to set.php. There is changes the value of the key that is defined in the GET (set.php?id=). The code above does work, but as soon as I refresh it, it changes the value back to the previous one. I have no idea why it does that.


Solution

  • You cannot persist data like that across multiple requests. At every request, PHP starts from scratch, again executing your config.php file, defining the variable.

    So if you do this request:

    set.php?id=13
    

    PHP does the necessary change, sends the page to the browser, and forgets about all your variables.

    So if you then call another page, or the same one with another id, then PHP will start with blank information, and will not know about the previous change for id 13.

    If you need this data to be retained across requests, there are several possibilities:

    If it only needs to be persisted per user, then use session variables. If on the other hand, it must be a global setting, the same for every user, then you should look to file storage, or to a database, like MySql.