is it possible??

$a= 5;
$b =10;
$c= "+"
$d= $a.$b.$c;

How can I do dynamic calculation like this. I know this code will not work. But
Just want to use opereater directly input through form. How can I prevent opreater to converting into string.

Recommended Answers

All 3 Replies

Thanks pritaeas very helpful tutorial.

Member Avatar for diafol

As Pritaeas states, eval() should be evil() !! You must escape and lock down ALL input if you're going to use eval(). ANother way to do this would be to work through a conditional:

function opClick($c, $a=0, $b=0){
    $allowed = array("+","-","/","*");
    $err = array(
        "div0" => "You can't divide by zero", 
        "wrongOp" => "This operator does not exist, please use +, -, / or *"
    );
    if(in_array($c,$allowed)){
        $a = floatval($a);
        $b = floatval($b);

        switch $c{
            case '+':
                $ans = $a + $b; 
                break;
            case '-':
                $ans = $a - $b; 
                break;
            case '/':
                $ans = ($b !== 0) ? $a / $b : $err['div0']; 
                break;
            case '*':
                $ans = $a * $b; 
                break;
        }
    }else{
        $ans = $err['wrongOp'];
    }
    return $ans;
}    


$a = 34;
$b = 2;
$c = '+';

echo "$a $c $b = " . opClick($c,$a,$b);

Just something off the top of my head. Not brilliant, but at least a option to eval(). In fact you could use eval() instead of the big switch:

function opClick($c, $a=0, $b=0){
    $allowed = array("+","-","/","*");
    $err = array(
        "div0" => "You can't divide by zero", 
        "wrongOp" => "This operator does not exist, please use +, -, / or *"
    );
    if(in_array($c,$allowed)){
        $a = floatval($a);
        $b = floatval($b);
        $ans = ($c == '/' && $b === 0) ? $err['div0'] : eval("$a $c $b");
    }else{
        $ans = $err['wrongOp'];
    }
    return $ans;
}    

$a = 34;
$b = 2;
$c = '+';

echo "$a $c $b = " . opClick($c,$a,$b);

However, I would use javascript for this type of simple calculation and if need be store the result in a form field (hidden or visible) which can then be sent to php (Ajax or normal method) if you need to use it in server-side process like DB manipulation.

commented: very nice answer +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.