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

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.


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);

Tags:

Php