How can functions be used as an alternative to storing repetitive if statements in variables in PHP?
Storing repetitive if statements in variables can lead to code duplication and make the code harder to maintain. Instead, functions can be used to encapsulate the logic of the if statements and make the code more modular and reusable.
// Using functions to replace repetitive if statements
function checkNumber($number) {
if ($number > 0) {
return "Positive";
} elseif ($number < 0) {
return "Negative";
} else {
return "Zero";
}
}
// Example usage
echo checkNumber(5); // Output: Positive
echo checkNumber(-3); // Output: Negative
echo checkNumber(0); // Output: Zero