Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global array in php

i have to function in two different files. one of them should add a new item to an array each time is called and the array should be accessible .what i did for it is :

function1(){

   global $array;

   $array[] = 'hi';

}

but it just create one item in array even if i call this function 4 times .

like image 800
hd. Avatar asked Dec 11 '10 09:12

hd.


People also ask

How do you make an array global?

There are two ways to reference a global variable in PHP: Use the global keyword at the start of every function that uses the variable. Use the $GLOBALS array.

How do you define a global array?

As in case of scalar variables, we can also use external or global arrays in a program, i. e., the arrays which are defined outside any function. These arrays have global scope. Thus, they can be used anywhere in the program. They are created in the beginning of program execution and last till its end.

How many types of global arrays are there in PHP?

There are about nine superglobal variables in PHP which are sometimes referred to as automatic globals .

What does global in PHP mean?

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.


1 Answers

What you did should work.

<?php

function function1(){

   global $array;

   $array[] = 'hi';

}
function1();
function1();
function1();
print_r($array);

Test it.

You probably have another problem. Please note that the lifetime of all variables is the current run of your script. They won't exist in a successive run. For that you need to use some sort of persistence like session, cookie, file system, database.

For more help post your complete code.

like image 136
Alin Purcaru Avatar answered Oct 20 '22 00:10

Alin Purcaru