PHP remove commas from numeric strings

user1082428 picture user1082428 · Feb 17, 2012 · Viewed 135.5k times · Source

In PHP, I have an array of variables that are ALL strings. Some of the values stored are numeric strings with commas.

What I need:

A way to trim the commas from strings, and ONLY do this for numeric strings. This isn't as straightforward as it looks. The main reason is that the following fails:

$a = "1,435";

if(is_numeric($a))
    $a = str_replace(',', '', $a);

This fails because $a = "1435" is numeric. But $a = "1,435" is not numeric. Because some of the strings I get will be regular sentences with commas, I can't run a string replace on every string.

Answer

JJJ picture JJJ · Feb 17, 2012

Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}