Jump to content

Convert string to operator


37seconds

Recommended Posts

I am trying to write a function that will evaluate 2 values, but the operator can be dynamic.

 

For example:

 

 
function evaluate($value1, $operator, $value2)
{
  if ($value1 { $operator } $value2)
  {
    return true;
  }
  else
  {
    return false;
  }
}

$test = evaluate(3, ">", 1);

 

Is there any way this can be done?

 

Thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/164853-convert-string-to-operator/
Share on other sites

I don't know of a way to do it just like that but you could use a switch statement and go from there...

 

<?php

switch ($operator) {
    case "<":
        //do less than comparison here and return
        break;
    case ">":
        //do greater than comparison here and return
        break;
    case "==":
        //you get the idea
        break;
}

?>

You could use eval (and the following code takes into consideration the difference between comparison & arithmetic operators.)

<pre><?php
function evaluate($value1, $operator, $value2) {
if(in_array($operator, array('+','-','*','/','%')))
	$t = 'return '.$value1.$operator.$value2.';';
else 
	$t = 'if('.$value1.$operator.$value2.') {return true;} else {return false;}';
return eval($t);
}
var_dump(evaluate(3, ">", 1));
var_dump(evaluate(3, "==", 1));
var_dump(evaluate(3, "+", 1));
var_dump(evaluate(3, "-", 1));
var_dump(evaluate(3, "/", 1));
var_dump(evaluate(3, "%", 1));
?></pre>

Outputs:

bool(true)

bool(false)

int(4)

int(2)

int(3)

int(0)

 

I'll be happy to add comments if you'd like. (edit for adding case examples)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.