在PHP中使用带有变量名的GET和POST数组

I'm struggling with variable variables in PHP. I have the following piece of code.

if($_GET["action"] == 1){
        $action = "_GET";
    }else{
        $action = "_POST";
}
...
${$action["lang_id"]}

I get the following errors:

  • Illegal string offset "lang_id" (but if I use directly the $_GET name it works properly)
  • udefined variable _ (yes, an underscore).

thanks in advance

${$action["lang_id"]}

Remember that the variable name goes between ${ and }, and that the variable name you are looking for is _GET or _POST.

You are trying to get the value of $action["lang_id"] and use that as the variable name… but $action is a string.

You need to use $action as the variable name and then read the property from the result.

${$action}["lang_id"]

… but you would probably be better off using $_REQUEST instead of variable variables. (Watch out for cookies with the same name as post or query string data though).

You can use $_REQUEST.

$_REQUEST is just combination of both $_GET and $_POST.

It works for both above two global variables.

So simply use $_REQUEST['lang_id']