While loop returns strings not integers

Hi everyone,

please help me with this. I’m returning some data from a database and looping it into an array.

while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$an_array = $row[‘whatever’];
}

The column data type is int yet when I do a var_dump of the array, the values are strings and not integers. Why? Maybe I’m missing something.

array (size=3)
  0 => string '5' (length=1)
  1 => string '8' (length=1)
  2 => string '12' (length=2)

Whatever the case may be, I’m trying to find a technique to add together the integers in the strings (5 + 8 + 12 = 25). Or if the values of the array are int, then I need a way to sum those ints.

Thank you, I hope someone has a solution!

Hi RedBishop,

Hope all is going well?

I believe PHP receives all values from MySQL as strings, regardless of the column type set in the table itself. It doesn’t make much difference in this situation though as PHP will automatically try to cast the values to integers when you perform any mathematical operation with them.

You could actually use MySQL’s SUM function to do the calculation for you in your query. Alternatively, if you already have an array of values that you want to sum, try PHP’s [fphp]array_sum[/fphp] function.

Hi fretburner,

Hope all is going well?

Yes, thank you.

I believe PHP receives all values from MySQL as strings, regardless of the column type set in the table itself. It doesn’t make much difference in this situation though as PHP will automatically try to cast the values to integers when you perform any mathematical operation with them.

Ok, thanks for clarifying that! I ended up using the array_sum function and it works pretty well.

Hope you are enjoying the weekend and thanks again for your help :slight_smile:

Cheers