Page 1 of 1

how to access global array (user defined)

Posted: Sun Jan 27, 2008 12:37 pm
by tawfiq
Hi,

I wonder if someone can help me understand this. I can access global variable from inside the function but not a global array. How do I add value to my array then?

Code: Select all

 
<?
$attributes[] = "";   // a blank array
$optionCounter=0;   // a global variable
 
 
function setOption($a){
 
global $optionCounter;  //accessing global variable - works fine
global $attributes // accessing global array - doesn't work
//add attribute to attribute array
$attributes[] = $a;  // this doesn't work either coz access to global array failed
 
//increment optionCounter by one
$optionCounter++;  // works fine
        
    
}
//test time
setOption("Size");
?>
 

Re: how to access global array (user defined)

Posted: Sun Jan 27, 2008 1:45 pm
by JAM
Change the functino abit. What does this tell you? At the bottom...

Code: Select all

function setOption($a) {
    print_r($GLOBALS);
}

Re: how to access global array (user defined)

Posted: Sun Jan 27, 2008 2:14 pm
by tawfiq
No Output at all

Re: how to access global array (user defined)

Posted: Sun Jan 27, 2008 2:22 pm
by JAM
Perhaps the use was unclear...

Code: Select all

<pre><?php
    error_reporting(E_ALL);
    $foo = array();
    $bar = 0;
    function setOption($a) {
        print_r($GLOBALS);
    }
    setOption();
?></pre>
That shows nothing?!

Re: how to access global array (user defined)

Posted: Sun Jan 27, 2008 2:24 pm
by JAM
Sorry, double post because the forum got fubared for some reason yesterday...

Re: how to access global array (user defined)

Posted: Mon Jan 28, 2008 1:04 am
by Kieran Huggins
there's a semicolon missing in your original example - is it there in your test code?

Re: how to access global array (user defined)

Posted: Mon Jan 28, 2008 6:04 am
by tawfiq
I have solved it :)

Thanks for your help.

Here is the code, I think changing from
$attributes[] = ""; to $attributes = array(); did the job

Code: Select all

 
 
//create an array with no element to store all the attributes (i.e options)
$attributes = array();
 
// ************ function to set option for product entry ***********
function setOption($a){
 
global $attributes;
 
//insert an element to the global array
$attributes[] = $a;
 
}
 
setOption("Size");
setOption("Colour");