Question
I am using a class which returns me the value of a particular row and cell of an excel spreadsheet. To build up an array of one column I am counting the rows and then looping through that number with a for()
loop and then using the $array[] = $value
to set the incrementing array object's value.
This works great if none of the values in a cell are 0
. The class returns me a number 0 so it's nothing to do with the class, I think it's the way I am looping through the rows and then assigning them to the array... I want to carry through the 0 value because I am creating graphs with the data afterwards, here is the code I have.
// Get Rainfall
$rainfall = array();
for($i=1;$i<=$count;$i++)
{
if($data->val($i,2) != 'Rainfall') // Check if not the column title
{
$rainfall[] = $data->val($i,2);
}
}
For your info $data
is the excel spreadsheet object and the method $data->val(row,col)
is what returns me the value. In this case I am getting data from column 2
.
Solution
Did you try an array_push() ?
array_push($rainfall, $data->val($i,2));
OTHER TIPS
I would use a strict comparison with the not identical operator here instead of using the not equals operator:
if($data->val($i,2) !== 'Rainfall')
If $data->val($i,2)
is an integer and you use ==
both sides will be cast to integers which would give you the result that all integers would work as you expect except for zero. Here's a summary of the difference between ==
and ===
when comparing the string "RainFall" with zero:
0 == "RainFall" : true
0 != "RainFall" : false
0 === "RainFall" : false
0 !== "RainFall" : true
I think that the array is treating the 0 like false, which could explain it not going into the array. Would something like this work (if you are using integers)?
(int)($data->val($i,2));
or
(float)($data->val($i,2);)
The problem lies in the if statement. You're trying to compare a string with an integer, which according to the PHP documentation will typecast both to integers.
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
You can read more here http://php.net/manual/en/language.operators.comparison.php.
Update: The if statement won't work in the case of 0
because (int)"Rainfall"
will by typecasted into 0
by PHP causing the statement to be if (0 != 0) { ... }
.
If $i
represents the row number, why don't you start from 2 instead of 1?