Best way to "switch arrays"

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I'm defining several arrays in the following format:

$farmanimals = array('farmanimal1' => 'horse', 'farmanimal2' => 'cow',
'farmanimal3' => 'chicken')
$housepets  =  array('housepet1' => 'dog', 'housepet2' => 'cat',
'housepet3' => 'bird')
$zooanimals = array('zooanimal1' => 'monkey', 'zooanimal2' => 'lion',
'zooanimal3' => 'zebra', 'zooanimal4' => 'giraffe')

I'm then running through a long text file, and detecting what part of
the file I'm in. If I'm in the farm animals section, I want to use the
$farmanimals array; if I'm in the house pets section, use the
$housepets arra, and so on.

Ideally, I may even have a different set of elements and then need to
create a variable on the fly to match the element name.

Can someone suggest the best method for changing the array to use,
without having to script  a different loop for each section of the
file I'm stepping through?



Re: Best way to "switch arrays"

javelin wrote:
Quoted text here. Click to load it
How do you "detect" the section?
You could have an array of arrays, keyed by a section name:
$animals['farm'] = array('horse', 'cow', 'chicken');
$animals['pets'] = array('dog', 'cat', 'bird');
$animals['zoo'] = array('monkey', 'lion', 'zebra'. 'giraffe');

Re: Best way to "switch arrays"

Quoted text here. Click to load it

The file will have a header line at the start of each section. I check
for the section, then I want to "switch" to the next array

The code looks like this at this point, hopefully this will help:

$file = fopen('sampledata1.txt','r');
 while (!feof($file)) {//step thru each line in file
   $nextline = fgets($file, $currentArray['linelength']); //using the
        echo $nextline . "<br>";
          if (strpos($nextline,"section2")) {
           # somehow, change the $currentdata array to use the next
one in line. Need to use the
           #   same name, "currentdata", for the array name.
        foreach ($currentdata as $col => $len){
                   # step thru the array elements, each which defines
the length of the next portion of the line
           print substr(startofline, $currentdata[$len]) ."<br>";


Re: Best way to "switch arrays"

Quoted text here. Click to load it

Well, I realized that the best way to deal with this is creating an
array of the arrays, returning it as a function. Then, I can easily
change arrays by referring to the index (I gave each array rec an
associated number that I can easily relate to my data).

Thanks for the help.

Re: Best way to "switch arrays"

javelin schrieb:
Quoted text here. Click to load it

I think, you know in wich section you are?

$actualarray = $farmanimals; // or $hose... or $zoo...
Now work with the $actualarray.

Site Timeline