tags:

views:

38

answers:

3

I cant seem to get eval to return a boolean value for '(4 > 5)'

Is this possible? If not how might I get this to work (without writing a parser)

I have tried this:

$v = eval('return (10 > 5)');
var_dump($v);

// Result = bool(false)

UPDATE

Thanks to @Pekka - I added a semicolon to the above code and it works.

+1  A: 

See the manual:

eval() returns NULL unless return is called in the evaluated code, in which case the value passed to return is returned. If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally. It is not possible to catch a parse error in eval() using set_error_handler().

It'll work like @mhitza already said in the comment. I would just add brackets to be safe:

    $x = eval('return (4 < 5);');
    echo $x;
Pekka
Nope - doesn't work.
ae
@ae works for me. I added a full example
Pekka
Yup - I forgot the semicolon - CHEERS!
ae
A: 

This has probably already been answered sufficiently...but what helps me is to always think of the eval in PHP as the entire line of code, and don't forget the semi-colon, e.g.

eval('\$myBooleanValue = 4 > 5;');
return $myBooleanValue;

Don't try stuff like this:

$myBooleanValue = eval('4 > 5');
Kevin Nelson
Yup - JavaScript's `eval()` can do the latter, but not PHP's.
Pekka
A: 

Please enable display_errors & a suitable error_reporting before turning to the community:

Parse error: syntax error, unexpected $end in -(2) : eval()'d code on line 1

Aha:

eval('return (10 > 5);');

Notice the ;.

Wrikken
I did - its not the most explanatory error message.
ae
If you did, you should've included it in your question. But for now: `unexpected $end` is always either a missing `;`, or unclosed `{` or `(`, so you can recognize it in future :)
Wrikken