lucyb lucyb - 3 months ago 19
HTML Question

PHP Factorial Issue

I am trying to learn PHP and compute the factorial of a number when given a input from a user, but I seem to be stumped. My first and last condition checkout but when I put a number bigger than 2 my result is always false, here is my code:



<!DOCTYPE html>
<html>
<head>
<title>Factorial</title>
</head>
<body>
<form action="" method="GET">
Enter Number: <input type="text" name="num"><br>
<input type="submit" name ="submit">
</form>
Factorial Of Your Number:
<?php
function factorial($n){

if (ctype_digit($n))
{
if ($n <= 1)
{
echo "1";
}
else
{
echo $n * factorial($n - 1);
}
}
else
{
echo "false";
}
}
if(isset($_GET['submit']))
{
$s = $_GET["num"];
factorial($s);
}
?>
</body>
</html>





I have tried editing many variations of this line echo $n * factorial($n - 1); but all result in false or an error and I can't seem to crack this. Any ideas? Note that I am trying to keep the php in the internal body not an externalphp file.

Answer

For your recursive function to work, it needs to return a number. Otherwise your function will try to calculate $n * null which throws an error.

function factorial($n){
    if ($n <= 1) {
        return 1;
    } else {
        return $n * factorial($n - 1);
    }
}

if (isset($_GET['submit'])) {
    $n = intval($_GET["num"]);
    echo factorial($n);
}
Comments