Skip to content
Advertisement

PHP: If number (with comma), convert it to right number format (with point)

I have an array of mixed values:

$row = array('Unspecified risk','Yes','8','3','2','13','none','-1,49','-2,51','-1,46','-1,54'); -1,94   -1,55

As you can see it contains text and both negative and positive comma-numbers.

I need to convert the numeric values to the right number format and leave the text values as is.

Now I’m looping over the values:

foreach ($row as $value) {
    // If $value is numeric, convert it to the 
    // right number format for use with MySQL (decimal(10,2))
    // If not, leave it be.
}

Two related questions I’ve investigated but cannot find a suitable solution.

Could anyone provide a practical example?

Advertisement

Answer

You don’t need to use regular expressions.

use str_replace() as you need to replace the ',' for a '.', and then use intval() or floatval() functions to get the numeric value. You can also use strstr() to look for the '.' and decide if using intval() or floatval()

Example:

$row = array('Unspecified risk', 'Yes', '8', '3', '2', '13', 'none', '-1,49', '-2,51', '-1,46', '-1,54');

    function toNumber($target){
        $switched = str_replace(',', '.', $target);
        if(is_numeric($target)){
            return intval($target);
        }elseif(is_numeric($switched)){
            return floatval($switched);
        } else {
            return $target;
        }
    }

    $row = array_map('toNumber', $row);

    var_dump($row);

We use str_replace() to replace the dot for the comma, this way it’s a international notation float, even if it’s on string, this way later on we can check if it’s numeric with is_numeric() <– this function is awesome as it detects from a string if it’s a number or not, no matter integer or float etc.

We use the is_numeric to check if the value is integer float or text and return the corresponding value using intval() or floatval() (the value without the replace applied will not return as a valid numeric, only after switching the , and . it will return true as numeric).

We use $row = array_map('toNumber', $row); to apply the changes to the array.

Profit xD

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement