What are some best practices for optimizing PHP code when dealing with complex combinatorial calculations like this?

When dealing with complex combinatorial calculations in PHP, it's important to optimize the code to improve performance. One way to do this is by using memoization, which stores the results of expensive function calls to avoid redundant calculations. Additionally, consider using bitwise operations for certain calculations to improve efficiency.

function factorial($n) {
    static $cache = [];
    
    if($n <= 1) {
        return 1;
    }
    
    if(isset($cache[$n])) {
        return $cache[$n];
    }
    
    $result = $n * factorial($n - 1);
    $cache[$n] = $result;
    
    return $result;
}

function nCr($n, $r) {
    return factorial($n) / (factorial($r) * factorial($n - $r));
}

$n = 5;
$r = 2;
echo nCr($n, $r);