Jump to content

[ resolved ] proplem with arrays


grenouille

Recommended Posts

Hi,

I wrote some code to retrieve data from a textfile. The code inserts data into a multidimensional array retrieved from the textfile. When printing out the array contents, it shows exactly what it's supposed to, so I know the code in itself is OK.

This is the code :

[code]
            $filename = "db.txt";
$handle = fopen($filename, "r");
$content = fread($handle, filesize($filename));
fclose($handle);
$bulk = get_string_between($content, "<sections>", "<sections>");
$global_array = explode(" || ", $bulk);
for($i=0; $i<count($global_array); $i++)
{
print $global_array[$i]."<br>";
$int_array = explode(" | ", $global_array[$i]);
$sect_arr[$i][0] = $int_array[0];
$sect_arr[$i][1] = $int_array[1];
}
[/code]

When I print out the contents of $sect_arr everything goes well.
However, when I put this code in a function and call that function, it doesn't show anything.
This is the function :

[code]
function CreateSectionArray($sect_arr)
{
$filename = "db.txt";
$handle = fopen($filename, "r");
$content = fread($handle, filesize($filename));
fclose($handle);
$bulk = get_string_between($content, "<sections>", "<sections>");
$global_array = explode(" || ", $bulk);
for($i=0; $i<count($global_array); $i++)
{
print $global_array[$i]."<br>";
$int_array = explode(" | ", $global_array[$i]);
$sect_arr[$i][0] = $int_array[0];
$sect_arr[$i][1] = $int_array[1];
}
}
[/code]

... and this is how the function is called :

[code]
CreateSectionArray($sections);
[/code]

When I print out this array $sections with print_r it seems to be empty. I suppose it's something very basic, but I just can't find it.

Your help would be very much appreciated.

Thnx in advance,

Grenouille
Link to comment
https://forums.phpfreaks.com/topic/29574-resolved-proplem-with-arrays/
Share on other sites

when you put it all in a function, the array variable is then local to the function.  you could either declare the array as a global, or just return the array from the function.

so the function call would look like

$array=CreateSectionArray();

and inside the funcion, before the last '}' you would add
return $sect_arr;

this way the function will return $sect_arr to $array;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.