How can PHP functions be optimized to avoid using the "global" keyword, as suggested in the responses?

Using the "global" keyword in PHP functions can lead to code that is difficult to maintain and test. To avoid this, you can pass variables as parameters to the function instead of relying on the global scope. This makes the function more self-contained and easier to understand.

// Avoid using global keyword by passing variables as parameters
function calculateTotal($itemPrices) {
    $total = 0;
    foreach ($itemPrices as $price) {
        $total += $price;
    }
    return $total;
}

$itemPrices = [10, 20, 30];
$total = calculateTotal($itemPrices);
echo "Total: " . $total;