Reputation: 103
(in PHP) Here is my problem, I would like to initialize an array in my class, have the constructor fill it, and then I can use the array's variables in other functions.. when I echo my array in the constructor it works perfectly, but the moment i try to echo it in another function, it gives me something very different.
class myProblem
{
public $phaseArray;
function myProblem()
{
$count1 = 0;
$metaFile = fopen( 'MyFile.txt', 'r' ) or exit( "Unable to open file!" );
while( !feof( $metaFile ) )
{
$this->phaseArray[0][$count1] = 0;
$this->phaseArray[1][$count1] = fgets( $metaFile );
echo $this->phaseArray[1][$count1], $count1, '</br>'; //this part displays well
$count1++;
}
close( $metaFile );
}
function displayError()
{
foreach( $this->phaseArray as $key => $value )
{
echo $key, $value, '</br>'; //this part does not show up correctly
}
echo $this->phaseArray[0][2]; //this part does not show up correctly
echo $this->phaseArray[1][1]; //this part does not show up correctly
}
}
Sorry about the indentation, I could not get it to work. The correct print out is(from the constructor); 0Apple 1Orange 3Pear 4Strawberry
but the second function displays; 0Array 1Array
0Array 0Array
any thoughts on what I am doing wrong? Thankyou for your time!
Upvotes: 1
Views: 83
Reputation: 304
Its correct the way it is displayed, you can decide if its wrong how you fill it or how you are reading the data out of it
You are creating an array with 2 dimensions, in which the second dimension is an array, too. So when you want to output all items of the second dimension, loop it through another foreach:
foreach( $this->phaseArray as $key => $values ) {
foreach( $values as $value ) {
echo $key, $value, '</br>'; //this part show up correctly
}
}
If you want to know how the array is structured, you can easily print it out with this:
echo "<pre>";
var_dump( $aVar );
echo "</pre>";
Upvotes: 1