Arno Nymo Arno Nymo - 8 months ago 44
PHP Question

Php array returns null?

I have php file which reads a file and puts it's contents in specific arrays. This php file is a file on it's own. So I included it on another page. When I want to access one of the arrays on the other site, the output is "array(0) { }". The var_dump on the file below, however returns a full array with all 6 items(as expected).

Here my php file:


$englishTranslationsList = array();
$germanTranslationsList = array();
$timestampList = array();
$noteList = array();

function extractTranslationsFromFile($file){

$handle = fopen($file, "r");
if ($handle){

while (($line = fgets($handle)) !== false) {

$notelist[] = $line;

$lineContent = substr($line, 3, strlen($line) - 1);

switch(substr($line, 0, 3)):

case "de:": $germanTranslationsList[] = $lineContent; break;
case "en:": $englishTranslationsList[] = $lineContent; break;
case "ts:": $timestampList[] = $lineContent; break;

default: break;





echo "<script>alert('ERROR')</script>";


echo var_dump($germanTranslationsList);



On the site where I included it, I used

<p><?php echo var_dump($germanTranslationsList); ?></p>

Which just shows an empty array as said above...
What have I done wrong? Is there a way to fix it?


You need to bring the global variables into the function's scope using the global keyword:


$englishTranslationsList = array();
$germanTranslationsList = array();
$timestampList = array();
$noteList = array();

function extractTranslationsFromFile($file) {
    global $englishTranslationsList;
    global $germanTranslationsList;
    global $timestampList;
    global $noteList;

    // ...