Errors with eval ()-php Tutorial

Source: Internet
Author: User
Tags parse error
Php eval () error ()

 '400','name'=>'kuke','time'=>'1024')";$res="1+3";var_dump($res);$v=eval($res);var_dump($v);echo $v;foreach($v as $key=>$val){echo $key."=".$val;}//-------------------------------------------echo "
";//--------------------------------------------$res=array('price'=>'400','name'=>'kuke','time'=>'1024');var_dump($res);echo "
";foreach($res as $key=>$val){echo $key."=".$val."
";}

This is the result
String (3) "1 + 3"
Parse error: syntax error, unexpected $ end in D: \ myweb \ array. php (5): eval () 'd code on line 1
Bool (false)
Warning: Invalid argument supplied for foreach () in D: \ myweb \ array. php on line 8

Array (3) {["price"] => string (3) "400" ["name"] => string (4) "kuke" ["time"] => string (4) "1024 "}
Price = 400
Name = kuke
Time = 1024
Can someone help me analyze why something went wrong?


Reply to discussion (solution)

$v = eval("return $res;");


Eval () returns NULL. unless a value is returned in the executed code, the function returns the value passed to return. If there is a parsing error in the executed code, eval () returns FALSE, and the subsequent code will be executed normally. You cannot use set_error_handler () to capture parsing errors in eval.

Definition and usage

The eval () function calculates the string according to the PHP code.

The string must be a valid PHP code and must end with a semicolon.

If the return statement is not called in the code string, NULL is returned. If a parsing error exists in the code, the eval () function returns false.
Therefore, write $ v = eval ("return $ res ;");

Warning: Invalid argument supplied for foreach () in D: \ myweb \ array. php on line 8
This error occurs because foreach can only traverse arrays and objects. If you input $ v as the bool value, an error is returned.

1.
$ Res = "1 + 3 ";
Eval ("\ $ v = \" $ res \";");
Var_dump ($ v );

2.
$ V no data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.