0

I am making very simple program in PHP . Tryig to addition first ..

But dont know ..

Here is code

<?php 
$a=12;
$b=10;
$c="+";

$res=$a."$c".$b;
echo $res;
?>

it output 12+10 as it is concecate..

$c is anything.

Any idea how to do this

2
  • 2
    possible duplicate of Numeric operation using string Commented Jun 30, 2012 at 9:44
  • Why do you put $c into quotes like "$c"? Also why do you put the operator into a variable? If you just write it without the string, it should work. Commented Jun 30, 2012 at 21:46

3 Answers 3

5

$c is now a string and not a expression "+" is not equal to +.

So:

$res=$a + $b;

If you would really need your structure you would have to do something evil like using eval() or you could do:

$a=12;
$b=10;
$operator='+';

switch($operator) {
  case '+':
    $res=$a + $b;
    break;
  case '-':
    $res=$a - $b;
    break;
}
Sign up to request clarification or add additional context in comments.

2 Comments

No i want to use only $c. not +
@user950276: If you want to learn PHP, learn to use it properly.
2

What do you want to do exactly?

If you have the operator as a string, you could try a switch statement:

<?php 
$a=12;
$b=10;
$c="+";

switch($c) {
  case '+': 
      $res = $a + $b;
      break;

  case '-':
      $res = $a - $b;
      break;
}
var_dump($res);
?>

Comments

0

Yes, also PHP has an eval(uate) function:

$res = eval($a . $c . $b);

Be sure that $a, $b and $c do not stem from form input, as eval can delete and so on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.