How do I turn a thousand-comma separated string representation of an integer into an integer value in PHP? (is there a general way to do it for other separators too?)
e.g. 1,000 -> 1000
Edit (Thanks @ghost) Ideally, decimals should be handled, but I could accept a solution that truncates at a decimal point.
list($name,$job,$location) = explode(',',$employee); Note: this will obviously only work if the string is in the format you specified. If you have any extra commas, or too few, then you'll have problems. It's also worth pointing out that PHP has dedicated functions for handling CSV formatted data.
PHP Casting Strings and Floats to Integers Sometimes you need to cast a numerical value into another data type. The (int), (integer), or intval() function are often used to convert a value to an integer.
If thats simple as it gets you could use filter_var()
:
$number = '1,000';
$number = (int) filter_var($number, FILTER_SANITIZE_NUMBER_INT);
var_dump($number);
Or
$number = '1,000.5669';
$number = (float) str_replace(',', '', $number);
var_dump($number);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With