PDA

View Full Version : Add to array with a loop


golden14
11-29-2006, 10:36 PM
Hello,

I'm a little stuck with this. I'm trying to use a loop to add items to an array, but I'm not quite sure how to predefine the size of an array without initially adding anything to it. I was reading in lines from a text doc, and wanted each line to be an item in the array.

Here is what I was trying, and it didnt seem to be adding to the array, only replacing the last item:



$fileId = `fopen "C:\\temp\\sample.txt" "r"`;
string $nextLine = `fgetline $fileId`;

while ( size( $nextLine ) > 0 )

{

int $i = 0;

global string $testArray[];

$testArray[$i] = $nextLine;

print $testArray[$i];

$nextLine = `fgetline $fileId`;

$i++;

}

fclose $fileId;

for ($item in $testArray)
{
print ($item + "\n");
}




Any help would be appreciated. Thanks.

djtomservo
11-30-2006, 12:39 AM
Here's a good way to do it:



//an empty array
string $array[] = {};
while( condition )
{
//now add the item to the last position in the array as defined by the size of the array
$array[ size( $array) ] = item to save;
}


Here's another way:



//an empty array
string $array[] = {};

//a pointer
int $i = 0;
while( condition )
{
//now add the item to the last position in the array as defined by the pointer
$array[ $i ] = item to save;

//now increment the pointer
$i += 1;
}



So you almost have it, the problem is where you set $i to 0 at the beginning of your loop. you want to set that outside the while statement, otherwise it's going to reset to 0 every iteration and you'll never get anywhere;)

golden14
11-30-2006, 03:23 PM
Ahh....I knew it had to be a small oversight. That worked fine, thanks for the help!

CGTalk Moderation
11-30-2006, 03:23 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.