Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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.

like image 533
markus Avatar asked Dec 11 '08 20:12

markus


People also ask

How do you change all values in an array?

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.

How can I get float in PHP?

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.

How can I get values from array in PHP?

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.

What is Floatval?

The floatval() function is used to convert a value to a float.


2 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);
like image 164
Greg Avatar answered Sep 16 '22 16:09

Greg


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.

like image 33
Kris Avatar answered Sep 18 '22 16:09

Kris