Search code examples
phparraysglobal-variables

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 .


Solution

  • 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.