What are best practices for handling arrays and variables within PHP functions to avoid errors and improve code efficiency?

When working with arrays and variables within PHP functions, it is important to properly handle input validation, error checking, and variable scoping to avoid errors and improve code efficiency. To achieve this, always check if the input parameters are of the expected type and handle any potential errors gracefully. Additionally, use meaningful variable names and avoid global variables to prevent conflicts and improve code readability.

function calculateSum(array $numbers) {
    $sum = 0;

    foreach ($numbers as $number) {
        if (is_numeric($number)) {
            $sum += $number;
        } else {
            // Handle invalid input gracefully
            return "Invalid input. Please provide an array of numbers.";
        }
    }

    return $sum;
}

// Example usage
$numbers = [1, 2, 3, 4, 5];
echo calculateSum($numbers); // Output: 15