Access and display array values in a function

Hi. I have a function A in which I created an array with values. I have a function B in which I want to access array values from the function A, and display them in a dropdown list.

I have went through the documentation of Variable scope, passing variables and arrays as function arguments, declaration of global variables. Can’t get around it and would love some more insight and guidance.

Here is my latest attempt (unsuccessful :frowning:)

Function A:

function cfwc_create_custom_field()  {
 $args_select_stone = array(
'options' => array('Stone' => 'Amethyst', 'Agate', 'Pink quartz', 'Bismuth', 'Bloodstone', 'Buddstone', 
    'Calcite', 'Dolomite', 'Fluorite', 'Hematite', 'Iolite', 'Jasper'),
);
}

Function B:

function cfwc_display_custom_field(&$args_select_stone) {
...
'echo html'
    foreach($args_select_stone['options']['Stone'] as $stones) {
'echo html'
    echo $stones;
...
}

I know that you cannot just access variables outside of the function scope, but I also realize that it is possible, I am just not able to do it myself (yet). Help appreciated

I think that you are looking for the return statement?

function cfwc_create_custom_field()  {
    return array(
       'options' => array('Stone' => 'Amethyst', 'Agate', 'Pink quartz', 'Bismuth', 'Bloodstone', 'Buddstone', 'Calcite', 'Dolomite', 'Fluorite', 'Hematite', 'Iolite', 'Jasper'),
);

$stones = cfwc_create_custom_field();
cfwc_display_custom_field($stones);

But … you should not use echo statements in functions for 99.9% of the time… keep that in mind for now.

Why are you putting just an array in a function?

You should examine global and local variables too.

Sponsor our Newsletter | Privacy Policy | Terms of Service