DrSheldonTrooper
DrSheldonTrooper

Reputation: 169

How to calc with operations in variable

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;
?>

Upvotes: 0

Views: 58

Answers (2)

RJParikh
RJParikh

Reputation: 4166

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

Upvotes: 2

Ikari
Ikari

Reputation: 3236

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

Upvotes: 2

Related Questions