Reputation:
I have a while loop that uses the fgetcsv function and iterates through a csv file until the end. In the loop I want to add a value from a specific column to a new array.
Everything works as it echos the value from the column that I need. However when I put the line in to add to the array it does not work. I have a HTML table that prints after the PHP code however when I use the line to add to the array it does not work.
I have looked on the internet and everything I have seen is doing it the way I have done so I am a little confused.
Here is my code:
$amountRecords = 0;
$totalValue = 0;
$valueArray = array();
$handle = fopen('data.csv', 'r');
// to skip the header names/values
fgetcsv($handle);
while($row = fgetcsv($handle, "\r"))
{
$valueArray[$amountRecords] += $row[1]; // THIS IS THE LINE THAT IS NOT WORKING
$totalValue = $totalValue + $row[1];
$amountRecords++;
}
Upvotes: 0
Views: 335
Reputation: 239291
There is some strangeness with your code. You're incrementing $amountRecords
each time, so you'll never access the same index in $valueArray
twice, yet, you're adding values to each element. Possibly you simply mean to assign the value with $valueArray[$amountRecords] = $row[1];
instead of +=
?
If that's the case, it looks like you're simply attempting to add the item onto the end of the array, extracting column 1 into its own array. You should use array_push
or array[]=
syntax for that:
while($row = fgetcsv($handle, "\r"))
{
// Add $row[1] to the end of $valueArray
$valueArray[] = $row[1];
$totalValue = $totalValue + $row[1];
}
The +=
operator is for adding something to an existing value. Typing a += b
is the same as typing a = a + b
. You should be using that operator on the next line, for example:
$totalValue += $row[1];
As a final suggestion, learn to do some basic debugging. If your loop isn't working, make it show you what it's doing during each iteration. Use var_dump
to inspect your variables and make sure they actually contain what you think they contain. Using var_dump($row)
would be especially useful in making sure that $row[1]
is the correct index.
echo "Before loop\n";
while($row = fgetcsv($handle, "\r"))
{
echo '$row contains: ';
var_dump($row);
$valueArray[] += $row[1]; // THIS IS THE LINE THAT IS NOT WORKING
echo '$valueArray now contains ':
var_dump($valueArray);
$totalValue = $totalValue + $row[1];
}
echo "After loop\n";
Upvotes: 2
Reputation: 95101
From my understand of your script $valueArray[$amountRecords] += $row[1];
would not make any logical sense because its dependent on $amountRecords ++;
which would always increase .
I think your script would work fine like this
while ( $row = fgetcsv($handle, "\r") ) {
$valueArray[] = $row[1]; // Put all Row[1] Into a array
$totalValue += $row[1]; // Sum total Value
$amountRecords ++; //Get Record Count
}
Upvotes: 0