Are there any best practices for handling recursive functions in PHP, especially when dealing with mathematical calculations?

When dealing with recursive functions in PHP, especially for mathematical calculations, it is important to ensure that the base case is properly defined to prevent infinite recursion. Additionally, it is recommended to optimize the function to avoid unnecessary calculations and improve performance.

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

// Example usage
echo factorial(5); // Outputs 120