...

View Full Version : How to make an array in a function global



nst
02-14-2006, 06:51 PM
Hi,

I have an array inside a function. What is the code in order to make it global?

It's about $stock_symbol[$i].
If I write global $stock_symbol[] it provokes an error.
Thanks.


function insert_data()
{
global $year, $date, $link_id;

$query = "INSERT INTO ref_calendar VALUES (NULL, '$date')";
mysql_query($query, $link_id);
$date_id = mysql_insert_id($link_id);

for($i = 1; $i < $l_count; $i++) {
$stock_symbol[$i] = substr($lines[$i], 0, 5);
$price_date[$i] = substr($lines[$i], 21, 10);

$query = "INSERT INTO stocks(stock_symbol) VALUES ('$stock_symbol[$i]')";
mysql_query($query, $link_id);
$query = "INSERT INTO share_prices VALUES (NULL, $date_id, '$stock_symbol[$i]', '$price_date[$i]')";
mysql_query($query, $link_id);
}
}

GJay
02-14-2006, 07:29 PM
$stock_symbol=array();
...some code maybe...

function yourFunction() {
global $stock_symbol;

//$stock_symbol is now available here and can be manipulated

}

yourfunction();
//$stock_symbol will include any changes if used here

nst
02-14-2006, 07:48 PM
Yes, it worked.

Thanks.:thumbsup:

Zegg90
02-14-2006, 07:58 PM
If you don't want to use globals, you can do something like this:



$somearray = new array();

function thisfunction($a) {
//$a is now the same as $somearray
}

//Now to call the function:
thisfunction(&$somearray);

A lot of people tell me that using globals is bad...


btw, you don't need to use &$somearray, just use $somearray if your PHP is version 5.

Kurashu
02-15-2006, 03:28 AM
Using globals isn't bad; it is when you don't know what you're doing that they can become dangerous. That is true for everything.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum