PHP script increment

Asked

Viewed 59 times

1

I wonder how I could create a PHP script that every time it was run it would increment and print that number. Example: In the first execution it shows the number 1. In the second time the number 2. In the third time the number 3. But in the fourth time it would have to return to the number 1.

  • That was right now I will implement in my project. Thank you very much.

  • The best way to thank you is to accept the answer that helped you the most ;)

2 answers

3

Yes, it is possible but you will have to save the number somewhere(database or even a file)

Example saving the number in a file:

// script.php
$numero = file_get_contents('arquivo_salva_numero');
if (!empty($numero) && $numero < 3) {
    $numero++;
} else {
    $numero = 1;
}
echo $numero;
file_put_contents('arquivo_salva_numero', $numero);

Every time you run "php script.php" it will read the file "arquivo_salva_numero", then increments and prints the number and saves the new number in the file again. This would be a way to implement, but as already mentioned depends on what you want to do.

0

Saving in a text file

Check if the file exists to avoid a PHP Warning:...

$arquivo="contaatetres.txt";
//verifica se o arquivo existe
if (file_exists($arquivo)) {

   //lê o conteúdo do arquivo
   $numero=file_get_contents($arquivo);

      if($numero<3){
          $numero++;
      }else{
          $numero=1;
      }
      
}else{
    $numero=1;
}

//Se o arquivo não existir é criado. Se existir é sobrescrito.
file_put_contents("contaatetres.txt", $numero);  


echo "O numero é $numero";

Browser other questions tagged

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