How can the code provided for calculating binomial coefficients be optimized for better performance in PHP?

The code provided for calculating binomial coefficients can be optimized for better performance in PHP by using memoization to store previously calculated values and avoid redundant calculations. By storing these values in an array, we can quickly retrieve them when needed, reducing the overall computational time.

function binomialCoefficient($n, $k) {
    static $memo = [];

    if ($k == 0 || $k == $n) {
        return 1;
    }

    if (isset($memo[$n][$k])) {
        return $memo[$n][$k];
    }

    $result = binomialCoefficient($n - 1, $k - 1) + binomialCoefficient($n - 1, $k);
    $memo[$n][$k] = $result;

    return $result;
}

// Example usage
$n = 5;
$k = 2;
echo binomialCoefficient($n, $k); // Output: 10