S
S
Senseich2018-04-04 19:49:10
PHP
Senseich, 2018-04-04 19:49:10

Is the PHP factorial calculation correct?

Hello! I have been learning PHP not so long ago and it always seems that the code is "clumpy", but I seem to be doing it according to the rules, with all the indents. And there is also the question of rationality of the decision. Can anyone look at an example, read the code (indentation, etc.) and is it possible to write something simpler?
There is a simple problem:

Create a simple form to enter a number.
If the user enters a number less than 0, then output the string: "The number must be 0 or greater than 0".
If the number is correct, then find and print the factorial of the entered number using the for loop.

I did it like this:
<?php

if (isset($_POST['numb'])) {

  $numb = htmlspecialchars($_POST['numb']);

  if (!is_numeric($numb)) echo "Не верно! Введите число!"; // Проверка на число

  else {

    if ($numb < 0) echo "Введите число больше нуля или ноль";

    elseif($numb > 1) {

      $factorial = 1;

      for ($i=1; $i <= $numb; $i++) {
        $factorial *= $i;	
      }
      echo "Факториал числа $numb: $factorial";	
    }
    else echo "Факториал числа $numb: 1";			
  }

}

?>

<form action="" method="post">
  <input type="text" name="numb" class="text">
  <input type="submit" value="Отправить">
</form>
<br>
<a href="http://myphp/Lesson_2_10/">Сбросить</a>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question