Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    nst
    nst is offline
    New Coder
    Join Date
    Jul 2005
    Posts
    57
    Thanks
    0
    Thanked 0 Times in 0 Posts

    How to make an array in a function global

    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.

    Code:
    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);
       }
    }
    Last edited by nst; 02-14-2006 at 07:11 PM.

  • #2
    Senior Coder
    Join Date
    Sep 2005
    Posts
    1,791
    Thanks
    5
    Thanked 36 Times in 35 Posts
    PHP Code:
    $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 

  • #3
    nst
    nst is offline
    New Coder
    Join Date
    Jul 2005
    Posts
    57
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Yes, it worked.

    Thanks.

  • #4
    New Coder
    Join Date
    Jan 2006
    Posts
    53
    Thanks
    0
    Thanked 0 Times in 0 Posts
    If you don't want to use globals, you can do something like this:

    PHP Code:
    $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.

  • #5
    Regular Coder
    Join Date
    Aug 2004
    Location
    The US of A
    Posts
    767
    Thanks
    1
    Thanked 0 Times in 0 Posts
    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.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •