0

I'm attempting to build an array from multiple records (unknown how many records there could be at any one time) using a while loop and array_fill but it's not working the way I had hoped it would. It's overwriting the array with each record and then the only data in the array after the while loop finishes execution, is the last record loaded.

$reward is the variable being overwritten. Driving me nuts! I would like to see it build $reward into a merged array consisting of the (in this instance) 3 records that I'm querying for. But it's ending up being the last record found. What am I doing wrong?

while ($WhileLoop <= $PrizeCount) {
    print "<!-- Loop # [" . $WhileLoop . "] -->\n";
    $Prize1Credits = $PrizeRecord["Prize_Credits"];
    $print "<!-- Cred # [" . $Prize1Credits . "] -->\n";
    $Prize1ID = $PrizeRecord["Prize_ID"];
    print "<!-- ID # [" . $Prize1ID . "] -->\n";
    $reward = array_fill($ArrayIndex,$Prize1Credits,$Prize1ID);
    print "<!-- IND # [" . $ArrayIndex . "] -->\n";
    $ArrayIndex += $Prize1Credits;
    $WhileLoop++;
    $DBConnection->next_record();                
    $PrizeRecord = $DBConnection->Record;
 } 

1 Answer 1

1

As you said you are overriding $reward array. You can use + operator on arrays to keep adding new records to $reward:

in your while loop:

$reward += array_fill($ArrayIndex,$Prize1Credits,$Prize1ID);

But to make this code more readable I would prefer a loop:

for ($i = 0; $i < $Prize1Credits, $i++) {
  $reward[] = $Prize1ID;
}
// no need for $ArrayIndex
Sign up to request clarification or add additional context in comments.

2 Comments

One of the first things I tried was the += operand, which throws a fatal "you can't use that operand with an array" type message. However, your for loop (switched the comma to a semi-colon after Prize1Credits) worked like a charm. Thanks man!
You're welcome. by the way, why do you iterate with a custom variable $WhileLoop? Is it not possible to iterate until $DBConnection->next_record() returns a value like: while ($DBConnection->next_record()) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.