While PHP does not exceed count

Asked

Viewed 78 times

1

How do pro while identify that will exceed the count set in the form and pause before?

FORM:

<form method="get" action="exercico04.php">
Inicio: <input type="number" name="inicio" value="1" max="100" min="1"/><br/>
Final: <input type="number" name="final" value="1" max="100" min="1"/><br/>
Incremento:
<select name="incremento">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
<br>
<input type="submit" value="Contar" class="botao"/>

PHP:

$inis = isset($_GET["inicio"])?$_GET["inicio"]:0;
    $finis = isset($_GET["final"])?$_GET["final"]:0;
    $incris = isset($_GET["incremento"])?$_GET["incremento"]:0;

    if($inis < $finis){
        echo $inis . "  ";
        while($inis < $finis) {
            $inis+=$incris;
        echo $inis."  ";
    }
}else if($inis > $finis){
    echo $inis . ",";
    while($inis > $finis) {
            $inis-=$incris;
        echo $inis ."  ";
    }
}

In the case, for example, if I choose START 7, FINAL 45 and INCREMENT 4, it will count like this: 7 11 15 19 23 27 31 35 39 43 47

Only in this case, I want him to stop before he gets to 45, which would be case number 43. How do I do that?

  • End is less than start?

  • Everson. The whole PHP Code doesn’t want to appear there, but it would look like this: $Inis = isset($_GET["start"])? $_GET["start"]:0; $Finis = isset($_GET["final"])? $_GET["final"]:0; $incris = isset($_GET["increment"])? $_GET["increment"]:0; if($Inis < $Finis){ echo $Inis . " " ; while($Inis < $Finis) { $Inis+=$incris; echo $Inis." " ; } } Else if($Inis > $Finis){ echo $Inis . " ,"; while($Inis > $Finis) { $Inis-=$incris; echo $Inis ." " ; } }

3 answers

5


There are some errors in your code, for example if($inis $finis), this condition is invalid, another error is the condition of the while where while($inis > $finis) { if start is receiving 7 and end 45 will never enter the loop, last you are decreasing the start and not incrementing, see an example with the fixes:

$inis = isset($_GET["inicio"])?$_GET["inicio"]:0;
$finis = isset($_GET["final"])?$_GET["final"]:0;
$incris = isset($_GET["incremento"])?$_GET["incremento"]:0;

if($inis != 0 && $finis != 0 && $incris != 0){
   /*Verifica se o usuário não inverteu inicio e fim, se sim troca
   *Por exemplo: $inis = 45; $finis = 7;
   *Neste caso será necessário inverter as variáveis
   *
   */
   if($inis > $finis){
      $aux = $inis;//armazena o valor original de $inis na variável $aux = 45
      $inis = $finis; //$inis = 7
      $finis = $aux; //Agora recebe valor de $aux, ou seja $finis = 45
      //Depois dessa troca os valores de início e fim estarão corretos
      //$inis = 7;
      //$finis = 45;
   }

   while($inis < $finis) {
     echo $inis ."  "; // imprime o primeiro valor
     $inis+=$incris;//incrementa
     if($inis > $finis) {//se após incrementar $inis > $finis
       $inis = $finis;
       echo $inis ."  ";//imprime o $finis
     }  
   }
}

EXAMPLE IN IDEONE

  • It was badly formatted, now it’s OK

  • 1

    by placing one more check inside the WHILE loop you can control whether the variable is getting close to the value you want to stop; if( $Inis + $incris> 45 ) { break; } (you can replace the 45 with a variable

  • @Everson is an option

  • @Lucascarvalho see the edition instead of repeating the while, you can check the variables and make the exchange.

  • I don’t know if you’ve seen my edition, Abfurlan, but now it has the code I made. I did not understand two parts very well, the part to check if it is different from 0 and the creation of the variable $aux, could explain?

  • 1

    Checks if it is != 0 for the $inis = isset($_GET["inicio"])?$_GET["inicio"]:0; is a if condition that assigns zero to variable if there is no GET correct? I imagine that if you were not informed for some reason the code will not be executed, as for the variable $aux, is only used to make the exchange, if $inis > $finis, see my issue with the comments.

  • 1

    Thank you all! Mainly to you, abfurlan!

Show 2 more comments

4

Using a for

if($_GET["inicio"] != 0 && $_GET["final"] != 0 && $_GET["incremento"] != 0){
   $inis=$_GET["inicio"];
   $finis=$_GET["final"];
   $incris=$_GET["incremento"];


    for ($x = $inis; $x < $finis; $x=($x+$incris)) {

        if ($x == $inis){
            echo $inis ."  ";
        }else{
            $inis+=$incris;
            echo $inis ."  ";
        }
    }
}

The FOR repetition structure is used to execute a set of commands for a defined number of times. For this operator, an initial situation, a condition and an action to be performed are passed each time.

In general we inform a variable that serves as a replay counter, with its initial value, a condition to be met so that each repetition is executed and an increment to the counter.

Syntax of the FOR operator

for(valor inicial; condição; incremento)
{
  //comandos
}

Taking advantage of the fabulous idea of our abfurlan friend

"Checks if the user has not reversed start and end, if yes exchange"

Would look like this:

$inis = isset($_GET["inicio"])?$_GET["inicio"]:0;
$finis = isset($_GET["final"])?$_GET["final"]:0;
$incris = isset($_GET["incremento"])?$_GET["incremento"]:0;

if($inis != 0 && $finis != 0 && $incris != 0){
   if($inis > $finis){
      $aux = $inis;
      $inis = $finis;
      $finis = $aux;

   }

        for ($x = $inis; $x < $finis; $x=($x+$incris)) {

            if ($x == $inis){
                echo $inis ."  ";
            }else{
                $inis+=$incris;
                echo $inis ."  ";
            }
        }  

}

3

A simpler solution to do what you want is to use the range(), native.

That’s all you need:

// Trata o input:
$inicio = $_GET['inicio'] ?? 0;
$inicio = is_numeric($inicio) ? $inicio : 0;

$final = $_GET['final'] ?? 0;
$final = is_numeric($final) ? $final : 0;

$incremento = $_GET['incremento'] ?? 1;
$incremento = is_numeric($incremento) && $incremento != 0 ? $incremento : 1;

// Faz o mesmo que o `while`:
echo implode(' ', range($inicio, $final, $incremento));

Test it out here.


The range() will make you go from $inicio up to the $fim, if defined a $incremento he will "jump", he cannot be 0. He returns a array, for example a var_export(range(7, 45, 4)); results in:

array ( 0 => 7, 1 => 11, 2 => 15, 3 => 19, 4 => 23, 5 => 27, 6 => 31, 7 => 35, 8 => 39, 9 => 43 )

That way we have, 7 until 43, as you wish.

The implode() is made to join values, so we join everything with a (space) between them.

That way the result we have to implode(' ', range(7, 45, 4)) is just:

7 11 15 19 23 27 31 35 39 43

See the documentation of implode() clicking here and the documentation of range() here. It is worth remembering that the range() also serves for letters, a range('a', 'z') will result in the alphabet. ;)

Browser other questions tagged

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