How can negative numbers and non-integer values be handled when calculating factorials in PHP?

When calculating factorials in PHP, negative numbers and non-integer values can be handled by checking for these conditions before calculating the factorial. For negative numbers, you can return an error message or handle the situation based on your specific requirements. For non-integer values, you can round down to the nearest integer before calculating the factorial.

function factorial($n) {
    if ($n < 0) {
        return "Factorial is not defined for negative numbers.";
    }
    
    $n = floor($n);
    
    if ($n == 0) {
        return 1;
    } else {
        return $n * factorial($n - 1);
    }
}

// Test the factorial function
echo factorial(-5); // Output: Factorial is not defined for negative numbers.
echo factorial(5.5); // Output: 120