PHP: if the number (with a semicolon), convert it to the right number format (with a dot)

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 numerical values ​​to the desired format and leave the text values ​​as they are.

Now I iterate 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 that I researched but cannot find a suitable solution.

Can anyone provide a practical example?

+5
source share
3 answers

You do not need to use regular expressions.

str_replace(), ',' '.', intval() floatval() . strstr() '.' , intval() floatval()

:

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

str_replace() , float, , , is_numeric() < - , , , ..

is_numeric , float text intval() floatval() ( , , true ).

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

xD

+6
$row = array('Unspecified risk','Yes','8','3','2','13','none','-1,49','-2,51','-1,46','-1,54');
    foreach($row as $key => $var) {
        if(strstr($var, ",") && !is_numeric($var)) {
            $var1 = str_replace(",","", $var);
            if(is_numeric($var1)) {
                $decimal = strstr($var, ',', TRUE);
                $digits = str_replace($decimal, "", $var1);
                $finalValue =  $digits * pow(10,$decimal);
                $row[$key] = $finalValue;
            }
        }
    }
    echo "<pre>"; print_r($row);

. php 5.3 php 5.3 +

+1

Use is_numericfor testing and number_formatformatting.

foreach ($row as &$value) {
    $number = str_replace(',','.');
    if(is_numeric($number))
        $value = number_format($number, 2, '.', '');
}
unset($value);
0
source

All Articles