What are the best practices for passing variables in PHP functions to prevent data loss or incorrect formatting?

When passing variables in PHP functions, it is important to use proper data types and avoid passing variables by reference unless necessary. To prevent data loss or incorrect formatting, it is recommended to validate input data before passing it to a function and to return values explicitly rather than relying on global variables.

// Example of passing variables in PHP functions with proper validation and return values

function calculateTotal($quantity, $price) {
    // Validate input data
    if (!is_numeric($quantity) || !is_numeric($price)) {
        return false;
    }

    // Calculate total
    $total = $quantity * $price;

    return $total;
}

// Usage
$quantity = 5;
$price = 10.99;

$total = calculateTotal($quantity, $price);

if ($total !== false) {
    echo "Total: $" . $total;
} else {
    echo "Invalid input data";
}