0

is there a way in PHP to calc if the operations are in variables as strings? Like this:

<?php
    $number1=5;
    $number2=10;
    $operations="+";

    $result = $number1 . $operations . $number2;
?>
RJParikh
  • 4,096
  • 1
  • 19
  • 36
DrSheldonTrooper
  • 161
  • 2
  • 12

2 Answers2

2

Use eval().

Note: Avoid eval() It is not safe. Its Potential unsafe.

<?php

$number1=5;
$number2=10;
$operations="+";

$result= $number1.$operations.$number2;

echo eval("echo $result;");

Output

15

Demo: Click Here

RJParikh
  • 4,096
  • 1
  • 19
  • 36
2

Assuming that the code you've given is a pseudo-code...

Given you have a limited set of operations that can be used, you can use switch case.

Using eval() can be a security issue if you are using user input for it...

A switch case example would be:

<?php

$operations = [
    '+' => "add",
    '-' => "subtract"
];

// The numbers
$n1 = 6;
$n2 = 3;
// Your operation
$op = "+";

switch($operations[$op]) {
    case "add":
        // add the nos
        echo $n1 + $n2;
        break;
    case "subtract":
        // subtract the nos
        echo $n1 - $n2;
        break;
    default:
        // we can't handle other operators
        throw new RuntimeException();
        break;
}

In action

Ikari
  • 3,176
  • 3
  • 29
  • 34
  • yeah I did it like this before but I work with a user input and i dont want to create to many switch cases or ifs – DrSheldonTrooper Jun 30 '17 at 08:43
  • yeah... so if you are processing user input, you SHOULD NEVER use eval... – Ikari Jun 30 '17 at 08:46
  • 2
    @DrSheldonTrooper don't use eval() when processing user input. Use a switch instead. Here an explanation about eval() https://stackoverflow.com/questions/951373/when-is-eval-evil-in-php – Companjo Jun 30 '17 at 09:23