Skip to content
Advertisement

Use php function in php form

I am new in php, I am solving one task.

  • Create a form with 2 text fields to enter only numbers (treat) and will mean number and power.
  • After pressing the button the result is displayed on the same page, and the result is determined by recursive function
  • in case you forget to enter a number, the number 2 will be inserted automatically.

I have this for now, but I don’t know how to proceed. Can you advise me please?

<!DOCTYPE html>
<html>
<head>
    <title>Task</title>
</head>
<body>
<form method="post">  
Input number:  
<input type="number" name="number1" /><br><br>  
Input power:  
<input type="number" name="number2" /><br><br>  
<input  type="submit" name="submit" value="Submit">  
</form>  
<?php 
    header("Content-Type: text/html; charset=windows-1250");
    if(isset($_POST['submit']))  
    {  
        $number1 = $_POST['number1'];  
        $number2 = $_POST['number2'];
        echo(pow($number1,$number2) . "<br>");
    }
         
?>  

 
</body>
</html>

Advertisement

Answer

I think you are missing a key concept here. What is recursion.

A recursive function is a function that calls itself during its execution. https://en.wikipedia.org/wiki/Recursion_(computer_science)

For your question this is an acceptable solution I believe:

<!DOCTYPE html>
<html>
<head>
    <title>Task</title>
</head>
<body>
<form method="post">
    Input number:
    <input type="number" name="number1" /><br><br>
    Input power:
    <input type="number" name="number2" /><br><br>
    <input  type="submit" name="submit" value="Submit">
</form>
<?php

function pow_recursion($number, $power) {
    if ($power == 0) {
        return 1;
    } else {
        return $number * pow_recursion($number, $power - 1);
    }
}

if(isset($_POST['submit']))
{
    $number1 = $_POST['number1'];
    $number2 = $_POST['number2'];

    if (!$number2) {
        $number2 = 2;
    }

    echo(pow_recursion($number1, $number2) . "<br>");
}

?>


</body>
</html>

Another implementation of the recursive function is

function pow_recursion($number, $power) {
    if ($power == 0) {
        return 1;
    } elseif ($power % 2 == 0) {
        $tmp = pow_recursion($number, intdiv($power, 2));
        return $tmp * $tmp;
    } else {
        return $number * pow_recursion($number, $power - 1);
    }
}

If I am not mistaken the difference in performance is N vs log(N).

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement