PHP script increment

0

I would like to know how I can create a PHP script that every time it was run it would increment and print this number. Example: In the first run it shows the number 1. The second time the number 2. The third time the number 3. However on the fourth time it would have to return to the number 1.

    
asked by anonymous 15.05.2018 / 19:20

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 to 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 "save_number", then increment and print the number and save the new number to the file again. This would be a way to implement, but as I mentioned before depends on what you want to do.

    
15.05.2018 / 19:38
0

Saving to a text file

  

Verify that 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";
    
15.05.2018 / 20:52