How can the issue of calling a function within itself be resolved to avoid an endless loop in PHP?

To avoid an endless loop when calling a function within itself in PHP, you can use a conditional statement to check for a base case that will terminate the recursive calls. This base case should be defined so that the function stops calling itself once a certain condition is met.

function factorial($n) {
    if ($n <= 1) {
        return 1; // Base case
    } else {
        return $n * factorial($n - 1); // Recursive call
    }
}

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