For some reason in one of my scripts I cannot access a global array in a function. The code is as follows: $sections=array('Your Details','Product Details'); function form1($values) { foreach($GLOBALS['sections'] as $key => $value) { //do something } } Code (markup): If I put the array inside the function and address it in the foreach loop as '$sections' it works fine. I didn't write the whole application and there are several INCLUDES in the script - I think somewhere on a lower level something has been disabled. I don't necessarily want to mess around with any of the core PHP files, but would like to get this to work - is there an alternative way of doing this? I would ideally prefer to keep the array outside of the function as there will be several functions that need to use the array...
If $sections is declared in a non-global context, then it won't be in $GLOBALS. That's almost surely your problem. You could do this: global $sections; $sections = array('Your Details','Product Details'); Code (markup): (inserting that "global" line before declaring $sections) But if you really wanted to do the job right, you'd figure out how to avoid having any globals at all.
Cheers mate, that has worked. Although in the past I have always managed to get it working without even declaring it as global! So how do I go about doing it the "right way", as you say?
There's nothing wrong with accessing a global variable within a function, the alternative is a mess of passing around pointers and needless copies of data. As long as you've declared a variable outside of the content of a function, or a namespace, you can declare the scope within any function for which to target that variable. There is no need to ever use the global keyword outside of a function or namespace. Stay away from "$GLOBALS['...']", that should only ever be used for debugging. $variable = array(); function one() { global $variable; // work with variable } function two() { global $variable; //work with variable } Code (markup):
Depending on your server set-up: before you define $variable as an array, you need to define it as a global. global $variable; $variable = array(); function one() { global $variable; // work with variable } function two() { global $variable; //work with variable } Code (markup):
In 5 years I've never once seen a situation where you had to use global outside of a function/method declaration. You've got an odd setup if you ask me.
It depends on the scope of the executing script. I do a lot of stuff with WordPress, so I've just had to get in the habit of doing it. I figured the OP might be doing something similiar.
Normally this would happen if include() is called from within a function. The entire include()d file is within that function's scope.