Reputation: 20223
I need an global array in php.
Here is the example:
global $array;
$array[0] = test;
if (something) function f1() else function f2();
function f1()
{
$array[0] = $array[0]." and test1";
}
function f2()
{
$array[0] = $array[0]." and test2";
}
But the problem is that the array is not affected as global but as local.
Do you have an idea why ?
Thank you.
Upvotes: 1
Views: 3169
Reputation: 14422
You have to call global inside each of the functions so PHP knows to look outside of the local scope.
function f1()
{
global $array;
$array[0] = $array[0]." and test1";
}
function f2()
{
global $array;
$array[0] = $array[0]." and test2";
}
Note in the 'real world' you should probably avoid using globals wherever possible as the globals can usually be solved with refactoring or redesign. Globals tend to lead towards a big ball of mud.
You should consider pass by reference
function f3(&$array)
{
$array[0] = $array[0]." and test3";
}
$array = array();
$array[0] = "test";
f3($array);
var_dump($array);
You can see an example at: http://codepad.org/27R5ZuKM
Upvotes: 5
Reputation: 21856
How about passing a parameter to a function and returning results?
avoid one big global spaghetti:
function f1( $array )
{
$array[0] = $array[0]." and test1";
return $array;
}
function f2( $array )
{
$array[0] = $array[0]." and test2";
return $array;
}
Upvotes: 2
Reputation: 2244
You need to declare the array as global in the local scope, i.e. in the function.
$array[0] = test;
if (something) function f1() else function f2();
function f1()
{
global $array;
$array[0] = $array[0]." and test1";
}
function f2()
{
global $array;
$array[0] = $array[0]." and test2";
}
Upvotes: 1