<html>
<! Calculate.php                                              >
<! Chapter 7, Oracle Database XE PHP Web Programming          >
<! by Michael McLaughlin                                      >
<!                                                            >
<! This demonstrates defining a function with formal          >
<! parameters and validating actual parameters by using the   >
<! func_num_args() and func_get_args() functions.             >
<head>
<title>
  Chapter 7 : Calculate.php
</title>
</head>
<body>
<?php
  // Define a global variable.
  GLOBAL $operands;

  // Assign the global variable an array of operands.
  $operands = array("+","-","*","/");

  // Call function with each operand.
  for ($i = 0;$i < count($operands);$i++)
  {
    // Print call and return value.
    print "[(\$a = 86, \$b = 6, \$operand = ".$operands[$i].")]";
    print "[".calculate(86,(6 + $i),$i,$operands)."]<br>";
  }

  // Define a function that does binary math operations.
  function calculate($a = 0, $b = 0,$op = 0,$operands)
  {
    // Check for three actual parameters.
    if (func_num_args() == 4)
    {
      // Check and override the default value.
      if (is_numeric(func_get_arg(0)))
        $a = func_get_arg(0);
      else
        return null;

      // Check and override the default value.
      if (is_numeric(func_get_arg(1)))
        $b = func_get_arg(1);
      else
        return null;

      // Check and override the default value and choose operation.
      if ((is_numeric(func_get_arg(2))) &&
          (array_key_exists(func_get_arg(2),$operands)))
      {
          // Declare operand.
          $op = $operands[func_get_arg(2)];

          // Apply formula based on operand.
          switch (true)
          {
            case ($op == "+"):
              return (float) $a + $b;
            case ($op == "-"):
              return (float) $a - $b;
            case ($op == "*"):
              return (float) $a * $b;
            case ($op == "/"):
              return round((float) $a / $b,2);
          }
      }
      else
      {
        // Return a null argument error.
        return null;
      }
    }
    else
    {
      // Return a null argument error.
      return null;
    }
  }
?>
</body>
</html>