1

I'm creating an array outside of my PHP function and calling global inside the function but my function fails to see the array. The function is also called recursively. Any idea what I'm doing wrong?

    $node_types = array( 1 => 'testproject',
                         2 => 'testsuite',
                         3 => 'testcase');


function get_subtree($node_id,&$node_list) {

    global $node_types;

    foreach ($node_types as $key)  { 
        echo("node_types: " . $key . "<BR>"); 
    }

    ....

    get_subtree($node_id,$node_list);
} 

My error:

Notice: Undefined variable: node_types in ...

Thanks

user1216398
  • 1,890
  • 13
  • 32
  • 40
  • Related: [Declaring a global array](https://stackoverflow.com/questions/12876222/declaring-a-global-array) – ggorlen Apr 11 '23 at 02:41

4 Answers4

5

Put

global $node_types;

above the array definition as well as inside the function.

Matt Gibson
  • 14,616
  • 7
  • 47
  • 79
1

Declaring an array within a function will create a new array each time the function is used and the scope of the array is only as long as the function. The Global array must be declared outside of functions. So in this case should be placed before at he top of the example.

Darren Burgess
  • 4,200
  • 6
  • 27
  • 43
0

Don't use global $node_types inside your function. It will create new variable, so your function will use the null variable instead of the one you have globally.

GoSmash
  • 1,096
  • 1
  • 11
  • 38
-5

My guess, you placed the global definition after the function call.