markus
markus

Reputation: 40695

How can I convert all values of an array to floats in 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:

Upvotes: 11

Views: 20453

Answers (5)

Parteek Kumar Kherpa
Parteek Kumar Kherpa

Reputation: 195

I found an easy way for this operation. You can do this just by adding foreach loop to your code. foreach loop is used to fetch your array string data one by one. and then, you can simply convert this by function number_format. i used 2 place after convert to float value. i.e it used to print value after dot value 2 place.

$example = array("12.20", "15.05", "55.70");
foreach ($example as $float) {
    $update_value = number_format($float, 2);
    echo $update_value . "<br>";
}

Upvotes: 0

rg88
rg88

Reputation: 20977

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

Upvotes: 0

Greg
Greg

Reputation: 321786

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

Upvotes: 32

troelskn
troelskn

Reputation: 117587

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?

Upvotes: -1

Kris
Kris

Reputation: 41867

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.

Upvotes: 1

Related Questions