PHP: If number (with comma), convert it to right number format (with point)
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