Search code examples
phpfilearray-push

How to declare an array as global in PHP?


I need to write the contents of an array to a file, each time the page is loaded... I've created the array in index.php and pushing contents to the array in another ajax page.. But i couldn't access the array globally.. its showing an error as 'undefined variable $arr'..

Here's my code..

Index.php page...

<?php
    $arr = array();

    $ourFileName = "saved_data.txt";
    $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
    fwrite($ourFileHandle, "");

?>

Ajax page.....

<?php
    $name_full = $_GET['name_full'];
    $arr = $_GET['$arr'];

    array_push($arr,$name_full);
    /*------------To create a file-----------------*/
    $ourFileName = "saved_data.txt";
    $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
    /*---------To save data in the file------------*/
    foreach($arr as $key => $value)
    {
        fwrite($ourFileHandle, $value);
    }
    fwrite($ourFileHandle, ',');
    fclose($ourFileHandle);
    echo $name_full;
?>

what else should i do to make this array global...


Solution

  • in ajax page declare $arr as, global $arr; and see if this works, but i doubt this don't work because each time the page is loaded, the array gets reset, Why dont you use session for this?