Cody Raspien Cody Raspien - 5 months ago 9
PHP Question

Is there a way to check for integers when there are commas in the value?

Typical values that are stored in my DB table as follows:

$value1 = "123,232,453";
$value2 = "123,232,453.45";


Commas and decimals. I have to detect if there has been any error in data entry after the data has been uploaded. The uploading process is a blackbox to me and it's likely that there is a number_format going on there.

I tried

ctype_digit($value1)


to check but the commas are not being of any help.

Is there a way to check for integers when there are commas in the value?

Answer

You can simply strip out the commas by treating the input as a string:

$value1 = str_replace(',', '', $value1);

Then you can check for integers using a regular expression:

if (preg_match('/^-?\d+$/', $value1)) {
    ...
}

Or, if decimals are allowed, you can use is_numeric()

if (is_numeric($value1)) {
    ...
}