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;
?>
1
  • 1
    I get it, this is just an example, but still... number1=5 -> $number1=5; Commented Jun 30, 2017 at 8:26

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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
yeah... so if you are processing user input, you SHOULD NEVER use eval...
@DrSheldonTrooper don't use eval() when processing user input. Use a switch instead. Here an explanation about eval() stackoverflow.com/questions/951373/when-is-eval-evil-in-php
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

5 Comments

ty, didn't knew about eval
Yes but as per questioner requirement I am helping. @Companjo
@RJParikh i understand, but it's better to inform him about the security risks too. Beside that, a switch is a better and safe alternative.
Ok, I forgot it. I have added note. @Companjo

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.