What are some best practices for handling recursive functions in PHP to ensure proper return values and functionality?

When working with recursive functions in PHP, it is important to ensure that the function returns the correct values and behaves as expected. One common issue with recursive functions is not properly handling the return values at each recursive call, which can lead to unexpected results. To address this, it is crucial to make sure that the function returns the correct value at each level of recursion, and that the base case is properly defined to stop the recursion when needed.

// Example of a recursive function to calculate the factorial of a number
function factorial($n) {
    if ($n <= 1) {
        return 1; // Base case: return 1 when $n is 0 or 1
    } else {
        return $n * factorial($n - 1); // Recursive call to calculate factorial
    }
}

// Test the factorial function
echo factorial(5); // Output: 120