Skip to content
Advertisement

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

I have an array of mixed values:

JavaScript

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:

JavaScript

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:

JavaScript

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