What are the potential pitfalls of using PHP to calculate capacity, as seen in the example provided?
When using PHP to calculate capacity, one potential pitfall is not properly handling errors or edge cases, such as dividing by zero or passing invalid input. To solve this, it is important to add proper validation checks and error handling to ensure the calculation is accurate and does not break the script.
// Validate input before performing capacity calculation
function calculateCapacity($totalCapacity, $usedCapacity) {
// Check if total capacity is zero to avoid division by zero error
if ($totalCapacity == 0) {
return "Total capacity cannot be zero";
}
// Check if used capacity is negative or greater than total capacity
if ($usedCapacity < 0 || $usedCapacity > $totalCapacity) {
return "Invalid used capacity value";
}
// Calculate capacity percentage
$capacityPercentage = ($usedCapacity / $totalCapacity) * 100;
return $capacityPercentage;
}
// Example usage
$totalCapacity = 100;
$usedCapacity = 50;
echo calculateCapacity($totalCapacity, $usedCapacity) . "%";