By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,278 Members | 1,342 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,278 IT Pros & Developers. It's quick & easy.

Evaluating a string as an expression

P: 6
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
Oct 6 '08 #1
Share this Question
Share on Google+
6 Replies


Markus
Expert 5K+
P: 6,050
Check out eval().

There may be a more elegant way than this.

Expand|Select|Wrap|Line Numbers
  1. $exp = '1 > 6';
  2.  
  3. $exp_eval = "if( $exp ) echo 'true'; else echo 'false';";
  4.  
  5. eval($exp_eval);
Oct 6 '08 #2

P: 6
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 :-

Expand|Select|Wrap|Line Numbers
  1. $str = '1 > 6' ;
  2. $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.
Oct 6 '08 #3

Markus
Expert 5K+
P: 6,050
Haha, okay.

See you around.

Mark.
Oct 6 '08 #4

pbmods
Expert 5K+
P: 5,821
Heya, Eureka.

Check out PHP's version_compare() function (http://php.net/version_compare).
Oct 6 '08 #5

P: 6
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]
Oct 14 '08 #6

pbmods
Expert 5K+
P: 5,821
Looks like you need to nest your conditionals. Compare 6.0 and 8.5 first, then compare 4 and 5.
Oct 16 '08 #7

Post your reply

Sign in to post your reply or Sign up for a free account.