Milos Cuculovic
Milos Cuculovic

Reputation: 20223

PHP and global array

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

Answers (3)

Pez Cuckow
Pez Cuckow

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

JvdBerg
JvdBerg

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

geekman
geekman

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

Related Questions