ChenXiu Posted November 2, 2022 Share Posted November 2, 2022 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! Quote Link to comment https://forums.phpfreaks.com/topic/315484-array-question-brackets-within-brackets-syntax/ Share on other sites More sharing options...
kicken Posted November 2, 2022 Share Posted November 2, 2022 5 minutes ago, ChenXiu said: the following syntax does not work That syntax works just fine. Why do you think it doesn't? Quote Link to comment https://forums.phpfreaks.com/topic/315484-array-question-brackets-within-brackets-syntax/#findComment-1602163 Share on other sites More sharing options...
ginerjm Posted November 2, 2022 Share Posted November 2, 2022 Quote Quote Cause $_GET is NOT an element of $_SESSION Quote Link to comment https://forums.phpfreaks.com/topic/315484-array-question-brackets-within-brackets-syntax/#findComment-1602168 Share on other sites More sharing options...
Phi11W Posted November 2, 2022 Share Posted November 2, 2022 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. Quote Link to comment https://forums.phpfreaks.com/topic/315484-array-question-brackets-within-brackets-syntax/#findComment-1602169 Share on other sites More sharing options...
ginerjm Posted November 2, 2022 Share Posted November 2, 2022 I blew my answer. Should have drank a bit more coffee Quote Link to comment https://forums.phpfreaks.com/topic/315484-array-question-brackets-within-brackets-syntax/#findComment-1602172 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.