How can developers ensure that recursive functions in PHP do not result in infinite loops or excessive memory consumption?

Developers can ensure that recursive functions in PHP do not result in infinite loops or excessive memory consumption by implementing a base case that will terminate the recursion, ensuring that the function progresses towards the base case with each recursive call. Additionally, developers can optimize the function by reducing unnecessary calculations or storing intermediate results to prevent redundant computations.

function factorial($n) {
    if ($n <= 1) {
        return 1; // Base case to terminate recursion
    } else {
        return $n * factorial($n - 1); // Recursive call with reduced input
    }
}

// Example usage
echo factorial(5); // Output: 120