How to make two values switch in a variable without repeating

Asked

Viewed 61 times

1

have a variable $rt that you need to switch with each refresh of the page, but without repeating.

If the variable’s value is 0, on the next page update the value must be mandatory 1 and when updating the variable’s value is 0.

I have this code that’s my kickoff, but I can’t think much of this logic.

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

How can you help me?

I have to switch between the values 0 and 1

  • 1

    Have you considered saving the current value in a database? Will the value vary with each user access or for each user? If it is for each user do not see how to do without a database, or cookie!

  • @Celsomarigojr for all

  • @Celsomarigojojr I prefer to rearrange this script so that the values do not repeat

  • Think that if the value varies per session it could be set in a cookie to be checked the previous one. To set the next one. I think the question is very vague... try to explain your goal so that it is easier to suggest a solution.

1 answer

3


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 it persistence, at the end of some time the count is no longer stored and starts again. And it all depends on the user, if the user deletes the cookies or does not even have them active this does not work.

Can also do with cookies, this can give you more persistence than Session however also, as said above, 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 and store the data you need there

  • I have to switch between the values 1 and 2

  • 1

    @Gladisonneuzaperosini, edited

  • Error in Session: Warning: session_start() [Function.Session-start]: Cannot send Session cookie - headers already sent by (output Started at /home/exibirimoveiscom/public_html/guaraparivirtual/index.php:1) in /home/exibirimoveiscom/public_html/guaraparivirtual/index.php on line 4

  • 1

    What is here, both options should be at the top of the page always @Gladisonneuzaperosini. First of all, right on the line following the <?php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.