Evaluating a string as an expression – PHP

  php

Q(Question):

Hi,

I am a PHP coder, recently ran into a bit of a problem trying to evaluate expressions in PHP.

I have an expression which is stored in a string variable and when I try to evaluate it, it always returns a ‘TRUE’

Eg:
[PHP]
$str = ‘6.0 >= 8.5’ ;

if($str)
{
//do something
}
else
{
//do something else
}[/PHP]

The value(rather the expression) inside ‘str’ variable comes from the database and I am suppossed to check whether it returns a ‘TRUE’ or a ‘FALSE’, but it always evaluates to ‘TRUE’..

I also tried doing something like foll., still doesn’t work, always returns ‘TRUE’
[PHP]$a = 6.0 ;
$b = ‘>=’ ;
$c = 8.5 ;

if( (boolean) $a .$b .$c)
{
//do something
}
else
{
//do something else
}[/PHP]
The code is always treating the expression as a string and evaluating to ‘TRUE’, can anyone help me with a way of making the string work as an expression..

Many thanks,
Sib

A(Answer):

Check out eval().

There may be a more elegant way than this.

$exp = '1 > 6';
$exp_eval = "if( $exp ) echo 'true'; else echo 'false';";
eval($exp_eval);

A(Answer):

Hey Markus,

Thanks a lot for the reply, this solution would have perfectly with my requirement, however I was in a hurry to submit the code hence as a workaround I simply took my exp-string and fired a mysql query to evaluate the result :-

$str = '1 > 6' ;
$sql_exp = "SELECT $str as val" ;

I knew this wasn’t the best solution, but couldn’t think of anything else at the time 🙂

But, thanks a lot really, your help is much appreciated, will keep in mind for future reference.

—Sib.

A(Answer):

Haha, okay.

See you around.

Mark.

A(Answer):

Heya, Eureka.

Check out PHP’s version_compare() function (http://php.net/version_compare).

A(Answer):

Heya, Eureka.

Check out PHP’s version_compare() function (http://php.net/version_compare).

Hi,

Thanks for responding.

Yes, version_compare() too seems to be fine for evaluating simple expressions

[PHP]if (version_compare(‘6.0’, ‘8.5’, ‘>=’))
{
echo ‘yes’ ;
}
else
{
echo ‘no’ ;
} [/PHP]

But fails for bigger expressions…

[PHP]if (version_compare("(6.0<=8.5)", "(4<5)", "&&"))
{
echo ‘yes’ ;
}
else
{
echo ‘no’ ;
} [/PHP]

A(Answer):

Looks like you need to nest your conditionals. Compare 6.0 and 8.5 first, then compare 4 and 5.

LEAVE A COMMENT