How can form data be properly passed to a PHP function for factorial calculation using $_POST?
To properly pass form data to a PHP function for factorial calculation using $_POST, you need to access the form input value using $_POST['input_name'], then sanitize and validate the input before passing it to the factorial function. The factorial function should then calculate the factorial of the input and return the result.
<?php
// Validate and sanitize input
if(isset($_POST['number']) && is_numeric($_POST['number'])){
$input = intval($_POST['number']);
// Factorial function
function factorial($n){
if($n == 0){
return 1;
} else {
return $n * factorial($n - 1);
}
}
// Calculate factorial
$result = factorial($input);
echo "Factorial of $input is $result";
} else {
echo "Invalid input";
}
?>
Keywords
Related Questions
- How can the scope of variables be managed effectively within PHP functions to ensure access to necessary resources like database connections?
- What are the differences between using array_values and reset/next functions to extract values from a filtered array in PHP?
- What are the best practices for using mysqli bind_result and fetch_array functions in PHP to retrieve data from a database?