What are the best practices for improving the efficiency of a PHP function that calculates factorials?

When calculating factorials in PHP, one of the best practices for improving efficiency is to use a loop instead of recursion. Recursion can lead to stack overflow errors when dealing with large numbers, whereas a loop can handle larger calculations more efficiently. Additionally, using an iterative approach can reduce the overhead of function calls and improve overall performance.

function factorial($n) {
    $result = 1;
    for ($i = 1; $i <= $n; $i++) {
        $result *= $i;
    }
    return $result;
}

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