Home » Php » pdo – How can I convert all values of an array to floats in PHP?

pdo – How can I convert all values of an array to floats in PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am fetching an array of floats from my database but the array I get has converted the values to strings.

How can I convert them into floats again without looping through the array?
Alternatively, how can I fetch the values from the database without converting them to strings?


EDIT:

  • I am using the Zend Framework and I am using PDO_mysql. The values are stored one per column and that is a requirement so I can’t serialize them.

  • array_map('floatval', $array) only works on single dimensional arrays.

  • I can’t floatval the single elements when I use them because I have to pass an array to my flash chart.

  • The momentary, non-generic solution is to extract the rows and do array_map('floatval',$array) with each row.

How to&Answers:

You could use

$floats = array_map('floatval', $nonFloats);

There is the option PDO::ATTR_STRINGIFY_FETCHES but from what I remember, MySQL always has it as true

Edit: see Bug 44341 which confirms MySQL doesn’t support turning off stringify.

Edit: you can also map a custom function like this:

function toFloats($array)
{
    return array_map('floatval', $array);
}

$data = array_map('toFloats', $my2DArray);

Answer:

How are you getting your data? mysql, mysqli or PDO, some other way or even some other database?

you could use array_map with floatval like so:
$data = array_map('floatval', $data);
but that still executes a loop and i think it assumes you only have one column in your data.

you’re probably best of casting to float when you use your value, if you have to. php is likely to do a good job of interpreting it right anyway.

Answer:

LOL… are you working on the same project I am tharkun?

I just finished (last night) creating something, in a ZF based project, that uses pdo_mysql to retrieve and format data and then output it as xml for use in a flash piece. The values were going in as strings but needed to be floats.
Since I’m also the one who wrote the part that gets the data and the one who created the database I just made sure the data was converted to float before it went into the database.

I simply cast the values as float as part of some other formatting, for what it is worth.

protected function _c2f($input)
    {
        $input = (float)$input;
        $output = round(($input * 1.8) + 32, 2);

        return $output;
    }

Answer:

Not sure what you’re asking here? You can cast a string to a float, using (float) $string, but since PHP is dynamically typed, that will happen anyway, when needed. There is no reason to do an explicit cast.

What are you using floating point values for?