How to make two values toggle on a variable without repeating

1

I have a $ rt variable that needs to alternate every page refresh, but not repeated.

If the value of the variable is 0 , the next value of the page should be 1 and when updating the variable value .

I have this code that is my kick-start, but I can not think much about this logic.

if($rt==0)
{
$rt = 0;    
}else{
$rt = 1;        
}

How can you help me?

I have to switch between values 0 and 1

    
asked by anonymous 26.07.2016 / 19:40

1 answer

3

You can do with session :

session_start();
if(!isset($_SESSION['count'])) {
    $_SESSION['count'] = 0;
}
else {
    if($_SESSION['count'] == 0) {
        $_SESSION['count'] = 1;
    }
    else {
        $_SESSION['count'] = 0;
    }
}
echo $_SESSION['count']; // 0 ou 1

However this does not give you persistence, at the end of some time the count is no longer stored and resumes. And it all depends on the user, if the user deletes the cookies or does not even have them active this does not work.

You can also do with cookies , this is able to give you more persistence than session however also, as I said above, it depends on the user:

if(!isset($_COOKIE['count'])) {
    setcookie('count', 0, time()+99999); # time()+99999 é a data de expiração do cookie, quando deixa de estar ativo
}
else {
    if($_COOKIE['count'] == 0) {
        setcookie('count', 1, time()+99999);
    }
    else {
        setcookie('count', 0, time()+99999);
    }
}
echo (isset($_COOKIE['count'])) ? $_COOKIE['count'] : 0; // 0 ou 1

Note that both options should be at the top of the page, before any output.

If you really need persistence choose to connect to a database to store there the data you need

    
26.07.2016 / 19:49