I need help on two PHP exercises [closed]

-6
  • Display the sum of integers between 1 and N, where N must be entered by the user through a form

  • Display leap years between a range entered by the user.

  • asked by anonymous 16.09.2017 / 21:05

    2 answers

    1
    Assuming you already know how to create a form and get data from it, just use array_sum to add the values of an array and range to create the array from 1 to the maximum value (or create it in some other way) . For example:

    echo array_sum(range(1, (int)($_GET['N'] ?? 0)));
    

    Test this.

    The date() function tells you whether the year is leap year or not, using L , see the documentation . Add the use of this with the use of range and with the use of strtotime (or mktime ) you can create the date and detect if it is leap or not. For example:

    foreach(range((int)($_GET['Inicio'] ?? 1), (int)($_GET['Fim'] ?? 1)) as $ano){
        if(date('L', strtotime($ano.'-01-01'))){
            echo $ano . PHP_EOL;
        }
    }
    

    Try this.

    You can also make a mod 4 ( ($ano % 4) === 0 ) to know whether or not it is leap.

        
    16.09.2017 / 21:36
    0

    PHP

    if (isset($_POST["numero"])){
        $num=0;
        $cont=$_POST["numero"];
        $i = 1;
        while ($i <= $cont){
            $num=$num+$i;
            $i++;
        }
        echo "A soma dos números de 1 a $cont é ". $num;
    }
    

    HTML - Form

    <form action="" method="post">
        <input type="number" placeholder="Numero" name="numero" required>
        <button type="submit">Calcular</button>
    </form>
    

    Test here with php version - early php version 4.4.9

    Then change the version in Run on PHP version to the desired version and click on the Execute code

        
    16.09.2017 / 22:17