genu Posted July 2, 2008 Share Posted July 2, 2008 How can I access an array through a variable? for example: I have: $_GET['task'] = "january" and I have a predefined array like so: $january = array('test1','test2','test3'); how can I access the $janurary array based on the the value of $task? I tried: echo $task[0]; but returned just "j" instead of 'test1' is there another way to reference that $january array? Quote Link to comment https://forums.phpfreaks.com/topic/112939-solved-how-to-access-an-array/ Share on other sites More sharing options...
lemmin Posted July 2, 2008 Share Posted July 2, 2008 I think you want $_GET['task'] = $january; Quote Link to comment https://forums.phpfreaks.com/topic/112939-solved-how-to-access-an-array/#findComment-580140 Share on other sites More sharing options...
genu Posted July 2, 2008 Author Share Posted July 2, 2008 but I don't really know what month that $task is going to be. It could be February, March, April, etc... I have predefined arrays for each one...not just January. Quote Link to comment https://forums.phpfreaks.com/topic/112939-solved-how-to-access-an-array/#findComment-580143 Share on other sites More sharing options...
lemmin Posted July 2, 2008 Share Posted July 2, 2008 So are you saying that $_GET['task'] will hold the string for the name of the array? In that case you can do this: echo $$_GET['task'][0]; And that should display "test1" from the $january array; Quote Link to comment https://forums.phpfreaks.com/topic/112939-solved-how-to-access-an-array/#findComment-580147 Share on other sites More sharing options...
genu Posted July 2, 2008 Author Share Posted July 2, 2008 I tried this: <?php $array = 'test'; $test = array('test1','test2','test3'); echo $$array[0]; ?> but it doesn't return anything Quote Link to comment https://forums.phpfreaks.com/topic/112939-solved-how-to-access-an-array/#findComment-580159 Share on other sites More sharing options...
lemmin Posted July 2, 2008 Share Posted July 2, 2008 Woops, you're right! You need curly braces or else it looks for the variable variable as the character from the string. <?php $array = 'test'; $test = array('test1','test2','test3'); echo ${$array}[0]; ?> Quote Link to comment https://forums.phpfreaks.com/topic/112939-solved-how-to-access-an-array/#findComment-580164 Share on other sites More sharing options...
genu Posted July 2, 2008 Author Share Posted July 2, 2008 Thanks lemmin, that worked... Quote Link to comment https://forums.phpfreaks.com/topic/112939-solved-how-to-access-an-array/#findComment-580226 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.