Page 1 of 1

Dynamic Variable Reference

Posted: Thu Dec 25, 2008 6:35 pm
by hyzdufan
I need some help with this variable reference. First off, here is the code...

Code: Select all

    //lexington
    if($delta3[1] < 0)  //tents needed?
    {
      //let the search begin
      $r = 0;
      while(r < 14)
      {
        if($'delta' . {$lex[$r])}[1] > 0)  //extra tents exist
        {
         //will write this later
        }
        $r = $r + 1;
        }
 
With this statement giving me the trouble...

Code: Select all

if($'delta' . {$lex[$r])}[1] > 0)
 
I should probably use a FOR instead of WHILE with a counter, but one thing at a time, ya know? :)

I have a delta# arrays for 14 different sites. The lex array is a numerical nearest neighbor list to search other sites for extra equipment. I have a for loop that calls this statement until the needed equipment has been found in another site. Delta#[1] is for tents. $r is a counter incremented each time to go to the next nearest neighbor in the list. I figured I would get it working for just one piece of equipment before I did the rest!

So basically, need to know how to reference delta(lex[nearestinlist])[tents]. Each time it's called, we check the next nearest neighbor. I know, complicated explanation. Please help me!

Re: Dynamic Variable Reference

Posted: Thu Dec 25, 2008 6:50 pm
by requinix
Got your precedence mixed up.

Code: Select all

if(${"delta" . $lex[$r]}[1] > 0)  //extra tents exist
However you should really be making $delta a 2D array where $delta1 is actually $delta[1], $delta2 is $delta[2], and so on.
Then you'd have code like

Code: Select all

if($delta[$lex[$r]][1] > 0)  // extra tents exist

Re: Dynamic Variable Reference

Posted: Thu Dec 25, 2008 8:10 pm
by hyzdufan
I've never played around with multi-dimensional arrays before. I'll have to read up on them. Thanks so much for your help!