SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    361
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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.

    PHP Code:
    array (size=3)
      
    => string '5' (length=1)
      
    => string '8' (length=1)
      
    => 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!

  2. #2
    Community Advisor bronze trophy
    fretburner's Avatar
    Join Date
    Apr 2013
    Location
    Brazil
    Posts
    1,410
    Mentioned
    45 Post(s)
    Tagged
    12 Thread(s)
    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 array_sum function.
    "There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies."

  3. #3
    SitePoint Addict
    Join Date
    Jul 2013
    Location
    South of the equator, then turn left
    Posts
    361
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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


    Cheers


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •