-3

Possible Duplicate:
Build condition comparison for if statement

Is there a way to convert '<' (string character) into a < (comparison character)?


EDIT:
I know of another way of achieving the same result, but it's a little longer, and wanted to know if that shortcut will work.
Basically, the comparison character is retrieved from the database (it could be <, > or =) as string, and it's supposed to compare 2 numbers. I understand that I can write a couple of scenarios of checking what the character is, but I still wanted to check if that string character could be converted to its comparison equivalent before embarking on the longer route.

Community
  • 1
  • 1
Kneel-Before-ZOD
  • 4,141
  • 1
  • 24
  • 26

2 Answers2

0

The short answer is no.

However, have a look at version_compare, as it may do what you're after natively (depending on what you're trying to achieve).

If not, you could do the following:

function compare($string1, $string2, $operator) {
    $cmp = strnatcmp($string1, $string2);

    switch($operator) {
        case '>':  return ($cmp >  0);
        case '>=': return ($cmp >= 0);
        case '<':  return ($cmp <  0);
        case '<=': return ($cmp <= 0);
        // expand as necessary
    }
}
cmbuckley
  • 40,217
  • 9
  • 77
  • 91
0

The eval() function allows you to evaluate a string as PHP code. For example:

eval('echo 2 < 3');

will print 1.

VettelS
  • 1,204
  • 1
  • 9
  • 17
  • After the edit of the question this seems a rather dangerous option. If the comparison operation is retrieved (unchecked) from the database the `eval` could basically execute arbitrary php code, whatever was (malicously) written in the database. – Christian.K Dec 29 '11 at 17:33
  • Simply check that what is retrieved from the database is what you expect, before executing the eval(). eval() is only evil when it's implemented incorrectly and unsafely. – VettelS Dec 29 '11 at 17:39
  • @user705339 See, for instance, [when is eval evil in php?](http://stackoverflow.com/questions/951373/when-is-eval-evil-in-php), [Eval is dead! Long live Eval!](http://www.sitepoint.com/eval-is-dead-long-live-eval/), and [a comment on PHP's `eval` doc](http://us3.php.net/manual/en/function.eval.php#44008). However, there are cases [where `eval` needs to be used](http://stackoverflow.com/questions/3499672/when-if-ever-is-eval-not-evil). – Kevin Ji Dec 29 '11 at 18:41