V Posted May 16, 2010 Share Posted May 16, 2010 I'm experimenting with arrays and functions. The code I made is, function list_items() { $fruits = array('apples' => 'red', 'bananas' => 'yellow', 'grapes' => 'purple'); foreach($fruits as $fruit_key => $fruit_value) { echo "$fruit_key are $fruit_value<br />"; } $drinks = array('Soda' => 'kids', 'Coffee' => 'adults', 'Alcohol' => 'happy fun times'); foreach($drinks as $drinks_key => $drinks_value) { echo "$drinks_key is for $drinks_value<br />"; } } list_items(); so it lists both fruits and drinks but I'm trying to learn how to list just one category of items. I tried list_items($fruits, $drinks) in the function and called it as list_items($drinks); to list just the drinks but that just gives errors.. Can someone please tell me the correct way to achieve this? Link to comment https://forums.phpfreaks.com/topic/201923-passing-array-variables-into-function/ Share on other sites More sharing options...
teamatomic Posted May 16, 2010 Share Posted May 16, 2010 function list_items($type) { if($type == 'fruit || $type == 'both') { do fruity stuff } if($type == 'drinks' || $type == 'both') { do drinky stuff } } list_type('fruit'); HTH Teamatomic Link to comment https://forums.phpfreaks.com/topic/201923-passing-array-variables-into-function/#findComment-1059017 Share on other sites More sharing options...
V Posted May 16, 2010 Author Share Posted May 16, 2010 Thank you for the script! I'm kind of confused. What is 'both'? Will I need to create an array for it? and the list_type('fruit') function, I didn't have that before. Sorry for being a noob.. Link to comment https://forums.phpfreaks.com/topic/201923-passing-array-variables-into-function/#findComment-1059156 Share on other sites More sharing options...
kenrbnsn Posted May 16, 2010 Share Posted May 16, 2010 You should be defining the arrays outside of the function and then passing the array you want to echo into the function: <?php function list_items($ary) { foreach($ary as $key => $value) { echo "$key is for $value<br />"; } } $fruits = array('apples' => 'red', 'bananas' => 'yellow', 'grapes' => 'purple'); $drinks = array('Soda' => 'kids', 'Coffee' => 'adults', 'Alcohol' => 'happy fun times'); list_items($fruits); list_items($drinks); ?> Ken Link to comment https://forums.phpfreaks.com/topic/201923-passing-array-variables-into-function/#findComment-1059158 Share on other sites More sharing options...
V Posted May 17, 2010 Author Share Posted May 17, 2010 Kenrbnsn thanks! that makes a lot of sense Link to comment https://forums.phpfreaks.com/topic/201923-passing-array-variables-into-function/#findComment-1059261 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.