muppet77 Posted April 4, 2018 Share Posted April 4, 2018 (edited) Hi, I have $rankseasoncart[0] = 3; $rankseasoncart[1] = 4; $rankseasoncart[2] = 5; and i want to write a piece of code so i can call each one separately by having a variable inside the square brackets. This doesn't work at all $numbera=1; echo ${"rankseasoncart[".$numbera."]"}; what silly error have I made? if i do echo $rankseasoncart[1]; as a test, it works fine! thanks. Edited April 4, 2018 by muppet77 Quote Link to comment Share on other sites More sharing options...
requinix Posted April 4, 2018 Share Posted April 4, 2018 Variable variables are just that: for variables. Not array values. Regardless, there's no good reason to use variable variables here. Keep it as the array it is. Quote Link to comment Share on other sites More sharing options...
muppet77 Posted April 4, 2018 Author Share Posted April 4, 2018 Hi and thanks. It’s part of a bigger script where I need to change $numbera frequently. Can it be done? Quote Link to comment Share on other sites More sharing options...
Solution muppet77 Posted April 4, 2018 Author Solution Share Posted April 4, 2018 sorted. echo $rankseasoncart[$numbera]; Quote Link to comment Share on other sites More sharing options...
Psycho Posted April 4, 2018 Share Posted April 4, 2018 If you are wanting to reference specific indexes, then that would seem to me that those indexes have specific meanings. An incrementing integer index should typically be used for an array when the values are a list of the same types of objects (e.g. a list of products in a shopping cart). However, if the items in an array are distinct items that have specific meaning, then I would highly suggest using named indexes. An example could be an array that holds a user's last product, most ordered product, favorite product, etc. Using a numeric based index for those values requires anyone working on the code to "know" what each of those numeric indexes mean. It is far easier and intuitive to use something like this $rankseasoncart['last_prod'] = 3; $rankseasoncart['most_prod'] = 4; $rankseasoncart['favorite_prod'] = 5; Quote Link to comment 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.