NeverPhased
NeverPhased

Reputation: 1566

An array value empty although previously populated

Hi I'm am sure this is a silly mistake but I have been staring at this the past 20mins to no avail. I have an array balance[] that is populated with two values for balance[0] and balance[1]. These are populated within the first for loop however when I go to use these values outside after this the array balance[0] is empty.

Below is my code and output:

for ($i=0; $i<$counter; $i++){

$x = mysql_query("

SELECT `outputValue` FROM `output` WHERE `outputType`= 'balance' && `period`= '6' && teamID = '$ID[$i]'

")or die($x."<br/><br/>".mysql_error());

    // set ID's = to a variable and now get Outputs for each variable(teamID)

            $balance = array();


            $row = mysql_fetch_assoc($x);
            echo $i." = I<br/>";
            $balance[$i] = $row['outputValue'];
            echo "Team ".$i."Balance = ".$balance[$i]."<br/>";

}
for ($i=0; $i<$counter; $i++){
echo "Team ".$i."Balance = ".$balance[$i]."<br/>";
}

enter image description here

Upvotes: 1

Views: 65

Answers (2)

Philip Sheard
Philip Sheard

Reputation: 5825

Move the line

   $balance = array();

outside of the loop.

Upvotes: 1

penartur
penartur

Reputation: 9912

You're initializing the $balance inside of the loop. On each for loop iteration, the $balance value is rewritten with an empty array().

On the first iteration, the $balance is set to an empty array, and then the $balance[0] is set. On the second iteration, the $balance is set to an empty array again, and then the $balance[1] is set.

So, after the loop, the $balance will only contain one element at the index of $counter-1.

Upvotes: 1

Related Questions