1

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.

ae.
  • 1,670
  • 1
  • 14
  • 19

3 Answers3

4

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
  • 442,112
  • 142
  • 972
  • 1,088
1

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
  • 7,613
  • 4
  • 31
  • 42
  • Yup - JavaScript's `eval()` can do the latter, but not PHP's. – Pekka Oct 26 '10 at 21:37
  • Is your code still valid if `$myBooleanValue` has not been defined before the `eval()` statement? I have such a case in my code. – Kanwarbir Singh Jan 29 '20 at 20:24
  • 1
    @KanwarbirSingh, yes...I don't know of any quirks that would prohibit it from working like any other line of code. Since you can write `$myBooleanValue = 4 > 5` to initiate a variable, you can do the same thing inside an eval() – Kevin Nelson Feb 18 '20 at 00:23
1

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
  • 69,272
  • 8
  • 97
  • 136
  • 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 Oct 26 '10 at 21:47