Jump to content

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)

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.