469,270 Members | 1,117 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,270 developers. It's quick & easy.

How do I "global" an array?

moishy
104 100+
I have a function which adds strings to an array, but outside the function it didn't add the string to the array.

Example:

[PHP]function AddStringToArray($name,$string) {

$theArray[$name] = $string;

print "inside the function: ".$theArray[$name]."<p>";
}

AddStringToArray('abc','hello world!');

print "outside the function: ".$theArray['abc'];

{[/PHP]

The above will result:

inside the function: hello world!

outside the function:
Nov 17 '06 #1
4 65703
ronverdonk
4,258 Expert 4TB
As follows;
[php]<?php
$theArray = array();
function AddStringToArray($name,$string) {
global $theArray;
$theArray[$name] = $string;
print "inside the function: ".$theArray[$name]."<p>";
}
AddStringToArray('abc','hello world!');
print "outside the function: ".$theArray['abc'];
?>[/php]
Ronald :cool:
Nov 17 '06 #2
Velhari
46
I have a function which adds strings to an array, but outside the function it didn't add the string to the array.

Example:

[PHP]function AddStringToArray($name,$string) {

$theArray[$name] = $string;

print "inside the function: ".$theArray[$name]."<p>";
}

AddStringToArray('abc','hello world!');

print "outside the function: ".$theArray['abc'];

{[/PHP]

The above will result:

inside the function: hello world!

outside the function:
Hi,
You can access the arrays from outside the function by declaring the array as global.

I changed your code as follows to rectify your problem.... you can use this code to acheive your goal....

[PHP]function AddStringToArray($name,$string)
{
global $thestring;
$thestring[$name]=$string;
echo "Inside Function:".$thestring[$name]."<br>";
}
AddStringToArray('abc','hello world');
echo "Outside Function:".$thestring['abc'];[/PHP]

With Regards,
Velmurugan.H
Nov 17 '06 #3
moishy
104 100+
But it doesn't work if I call from another function:

[PHP]
// Whatever was said before...

function LoopArray() {

foreach ($theArray as $value){
// Do whatever...
}
[/PHP]

will output:
Warning: Invalid argument supplied for foreach()

-even though i GLOBALed the array!
Nov 17 '06 #4
ronverdonk
4,258 Expert 4TB
Yes it does! You must declare the array in your main program and declare it global in all functions that use it.

Ronald :cool:
Nov 17 '06 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

11 posts views Thread by mrbog | last post: by
1 post views Thread by Chris Stromberger | last post: by
9 posts views Thread by Javaman59 | last post: by
7 posts views Thread by twang090 | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.