0

we execute dynamic string IF condition in PHP eval() function but the answer is not assign in variable.

Please look below code :

$variable_1 = "if(3>4)";
$variable_1 = "1";
$variable_1 = "0";

$if_val = "$variable_1{ $return_if = $variable_2 } else { $return_if = $variable_3 }";
$final_if_ans = eval($if_val); 
3
  • 1
    Aside from your 3 variables having the same name, you can print out the resulting code by printing $if_val to see what you're actually running. $return_if is not defined either. Commented Aug 8, 2018 at 5:08
  • 1
    You should be really careful with using eval(), it can be a security risk and should be avoided at all costs! Commented Aug 8, 2018 at 5:10
  • 1
    In $if_val, $return_if is not defined and also you've missed ; in each condition which will also throw error. Commented Aug 8, 2018 at 5:16

2 Answers 2

3

Use the following code to get the desired result:

$variable_1 = "if(3>4)";
$variable_2 = "1";
$variable_3 = "0";

$if_val = "$variable_1{ return $variable_2; } else { return $variable_3; }";
$final_if_ans = eval($if_val); 
echo $final_if_ans;

Important: The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Sign up to request clarification or add additional context in comments.

Comments

0

You declared all variables as $variable_1. Change to $variable_2 and $variable_3

Change this

$variable_1 = "if(3>4)";
$variable_1 = "1";
$variable_1 = "0";

to

$variable_1 = "if(3>4)";
$variable_2 = "1";
$variable_3 = "0";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.