Tuesday, February 3, 2026
HomeLanguagesPHP eval() Function

PHP eval() Function

PHP 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 the above syntax 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. 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: 

php




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


Output:

My age is $age
My age is 20

Program 2: 

php




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


Output:

Geeks for Geeks

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

RELATED ARTICLES

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
124 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11980 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12066 POSTS0 COMMENTS
Shaida Kate Naidoo
6987 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6935 POSTS0 COMMENTS
Umr Jansen
6919 POSTS0 COMMENTS