0

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

2
  • You are assigning $action, the string "_GET" and then applying an array action Commented Jun 11, 2018 at 12:32
  • use $_REQUEST['lang_id'] Commented Jun 11, 2018 at 12:33

2 Answers 2

5
${$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).

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

2 Comments

How did you work out that that is what they want to do? The check for $_GET["action"] throws me off
@AntonyD'Andrea — I glanced at it and it seemed obvious. (Perhaps you are confused by $_GET being populated with query string data for any request and not something that is restricted to GET requests. Many people appear to have been tripped up by this poor choice of name for the variable).
0

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']

1 Comment

"$_REQUEST is just combination of both $_GET and $_POST" — "just"? No, not just. It is those and $_COOKIE.

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.