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?
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.
To change the value of all elements in an array:Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.
Method 1: Using floatval() function. Note: The floatval() function can be used to convert the string into float values . Return Value: This function returns a float. This float is generated by typecasting the value of the variable passed to it as a parameter.
The array_values() function returns an array containing all the values of an array. Tip: The returned array will have numeric keys, starting at 0 and increase by 1.
The floatval() function is used to convert a value to a float.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With