article

Sunday, June 9, 2013

Understanding PHP Functions

Understanding PHP Functions 

<?php 
function calculate($num1, $num2, $operation = '+')
{
    switch($operation)
    {
        case '+': // add
            return $num1 + $num2;
            break;
        case '-': // subtract
            return $num1 - $num2;
            break;
        case '*': // multiply
            return $num1 * $num2;
            break;
        case '/': // divide, make sure denominator is not zero
            return ($num2 == 0) ? 'Cannot divide by zero' : $num1 / $num2;
            break;
        default:  // Display error message for unknown operation ex 'a', 'b' etc.
            return 'Unkown Operation Fool!';
            break;
    }
}
?>
<html>
<body>
<?php
    echo '1 + 3 = ';
    echo calculate(1,3);
    echo '<br />';
    echo '9 x 5 = ';
    echo calculate(9,5,'*');
    echo '<br />';
    echo 'Division by zero test: ';
    echo calculate(10, 0, '/');
    echo '<br />';
?>
</body>
</html>

Related Post