PHP | eval() Function

The eval() function in PHP is an inbuilt function that evaluates a string as PHP code.

Syntax:

eval( $string )

Parameters: This function accepts a single parameter as shown in above syntax and and described below.

  • $string: It must consist of a valid PHP code to be evaluated but should not contain opening and closing PHP tags.

Note: All statements must be properly terminated using a semicolon. For example, initializing the string as ‘echo “Geeks for Geeks”‘ will cause a parse error. In order to rectify, need to initialize as ‘echo “Geeks for Geeks”;’.

Return Value: Returns NULL unless a return statement is called in the input string containing PHP code. Then the value is returned. In case of a parse error in the input string, the function returns FALSE.

Examples:

Input : $age = 20; $str = "I am $age years old"
        eval("\$str = \"$str\";");
Output : I am 20 years old

Input : $str = 'echo "Geeks for Geeks";';
        echo eval($str). "\n";
Output : Geeks for Geeks

Below programs illustrate the use of eval() function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$age = 20;
$str = 'My age is $age';
echo $str. "\n";
  
eval("\$str = \"$str\";");
echo $str. "\n";
?>

chevron_right


Output:

My age is $age
My age is 20

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
$str = 'echo "Geeks for Geeks";';
echo eval($str). "\n";
?>

chevron_right


Output:

Geeks for Geeks

Reference : http://php.net/manual/en/function.eval.php



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.