RE: [PHP] How do I make an array like this?
| From: | Rasmus Lerdorf | Date: | Wed, 12 Jul 2000 05:35:32 +0000 |
| Subject: | RE: [PHP] How do I make an array like this? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-6066@lists.php.net to get a copy of this message | ||
> > > Print $key." ".$cost." ".$thickness."<br>";
> > > //Works OK!
> > > $WallCab[$Key] = array($cost, $thickness);
> > > }
> > > $Key = "Mel341";
> > > //Print "<br>A ".$WallCab[$Key]."<br>"; //Does not
> > > work
They "Mel341" is not a valid key in that array. It may look like it is,
but watch out for leading or trailing whitespace. I suggest using:
$WallCab[trim($key)] = array($cost,$thickness);
Although I think you are somewhat confused on how arrays work given your
next question:
> > > Print "<br>B ".$WallCab[$Key][$cost]."<br>"; //Does
> > > not work
$cost is not an array index.
Say $key is Mel340, Mel341 and Mel342 in your top loop. Then this:
$WallCab[$key] = array('foo','bar');
when iterated over those 3 values of $key produces a $WallCab array that
looks like this:
$WallCab[Mel340] = Array
$WallCab[Mel341] = Array
$WallCab[Mel342] = Array
And Array in this case is a single-dimensional array that looks like this:
$array[0] = 'foo';
$array[1] = 'bar';
Now, to access an element directly, you can do:
echo $WallCab['Mel340'][0] which would display: foo
echo $WallCab['Mel340'][1] which would displat: bar
I think perhaps what you meant to do is:
$WallCab[$key] = array($cost=>$thickness);
Or more logically:
$WallCab[$key][$cost] = $thickness;
-Rasmus