Jump to content

Array Question: brackets within brackets syntax


ChenXiu

Recommended Posts

Arrays use brackets. What is the syntax if I wanted a bracketed variable inside brackets?

For example "https://www.example.com/index.php?animal=horse" has this $_GET variable:
$_GET["animal"]

Security vulnerabilities notwithstanding, the following syntax does not work:
echo $_SESSION[$_GET["animal"]];

I assume it does not work because it's a bracketed variable inside brackets.

What syntax makes this work?

Thank you!

Link to comment
Share on other sites

1 hour ago, ginerjm said:

Cause $_GET is NOT an element of $_SESSION

Think about how PHP works. 

The echo statement displays the result of an Expression. 

Expressions can be nested inside one another, so ... 

echo 1 + ( 2 + ( 3 * 4 ) ); 

... returns 15 (3 times 4, plus the 2, plus the 1). 

In your case, you have the same sort of nesting.  

echo $_SESSION[ $_GET["animal"] ];

First, PHP works out the value of $_GET[ "animal"], and then uses that to index into $_SESSION, and then echo's out the result of that.   
PHP expressions can be nested to almost any level, limited only by PHP's internal constraints and, more importantly, your own Sanity, when you come to try and read what you've created, even just a few days later!

You probably want to do some validation on the QueryString value (of "animal") being submitted, because it could be absolutely anything!  (Trust nothing that comes from the Client.)

Regards,
   Phill  W.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.