-2

I'm trying to declare a global array and put data in it with a function.

It works only if the global variable is a string but not if it's an array:

$data = iterate("USER361");
print_r($data);

function iterate($username) 
{
    global $gv_array;

    $sql = "select * from account where sponsor = '$username'";
    $result = mysql_query($sql);
        while($row = mysql_fetch_array($result)) 
        {
            $this_user = $row['username'];
            $this_name = $row['full_name'];
            $this_tier = $row['tier'];

            $my_array = array("username"=>$this_user,"name"=>$this_name,"tier"=>$this_tier);
            array_push($gv_array[],$my_array);

            iterate($row['username']);
        }

}//end of iterate

The error I get is:

PHP Warning: array_push() expects parameter 1 to be array, null given in /var/www/html/inc/code.php on line 29

Al.G.
  • 4,327
  • 6
  • 31
  • 56
  • 2
    Possible duplicate of [PHP How to access this array GLOBALLY?](http://stackoverflow.com/questions/11743275/php-how-to-access-this-array-globally) – Junius L Apr 02 '17 at 06:21
  • 2
    shouldn't this line `array_push($gv_array[],$my_array);` be `array_push($gv_array,$my_array);` –  Apr 02 '17 at 06:22
  • check here: http://stackoverflow.com/questions/12876222/declaring-a-global-array – Mubashar Iqbal Apr 02 '17 at 06:25
  • 1
    Flagging as `a problem that can no longer be reproduced or a simple typographical error` since the solution has nothing to do with globality of variables and using them inside functions. This also applies: `This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting.`. – Al.G. Apr 02 '17 at 12:59

1 Answers1

0

if $gv_array it's an array then the problem is here array_push($gv_array[],$my_array); remove the square brackets.

array_push($gv_array,$my_array);
Junius L
  • 15,881
  • 6
  • 52
  • 96