Passing the operator in

this is a simple problem, but i can’t figure it out;

‘op’ is a radio checkbox which has either */-+
if i echo it, it’s passing it fine.

$number1 = $_REQUEST['value1'];
$number2 = $_REQUEST['value2'];
$operator = $_REQUEST['op'];

[COLOR="Red"]$total = $number1 $operator $number2;[/COLOR]

if (empty($number1)){
echo "you have to set a number for the first field <br />";
}
if (empty($number2)){
echo "you have to set a number for the second field";
}
else{
echo "$number1 $operator $number2 = " . $total;
}

Now that’s pretty awesome :slight_smile:
I wouldn’t have thought of doing it that way, but I see the possible benefits. Nice!

The simple switch is a fast way of doing things, however you can try the Strategy pattern for a more robust OOP way. It allows for more complex manipualtion if you need it later.


public interface IOperation
{
  function Combine($first,$second);
}
/* create a class for each operation */

public class AddOperation implements IOPeration
{
 function Combine($first,$second)
{
 /* todo validate parameters  */
return $first+$second;
}
}

/* .... Factory ... */

public class OperationFactory
{
 public static function GetOperation($operator)
{
 switch ($operator)
{
  case "+": return new AddOperation();

 /*todo the other operations */

 default: throw new Exception("Operation not implented)";
}
}
}


/* in your controller */
$operation= OperationFactory::GetOperation($operator);
$result=$operation->Combine($value1,$value2);

Excuse my rusty php, it’s been a while since I’ve written any php code.

I’m not sure if that will work, you might need to use a switch statement:


switch($operator) {
    case '+' :
        $total = $number1 + $number2;
    break;
    case '-' :
        $total = $number1 - $number2;
    break;
    case '*' :
        $total = $number1 * $number2;
    break;
    case '/' :
        $total = $number1 / $number2;
    break;
    default :
        trigger_error('Unsupported operand: ' . $operator);
}

There might be a more concise method, but I don’t know about it :wink:

thank you, i am guessing now i can do this with a series of if/else statements too.

the oop version is interesting but too complex for my level. still appreciated.