Jump to content

passing array variables into function


V

Recommended Posts

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.