PHP: How to Convert a String to a Number

Updated: January 9, 2024 By: Guest Contributor Post a comment

Introduction

Interchanging data types is a fundamental skill in programming. In PHP, converting a string to a number is a common task, which can be as simple as adding zero or as nuanced as locale-aware parsing.

The Basics of Type Juggling

In PHP, type juggling allows for on-the-fly type conversion. You can use operators or settype() to convert string to int or float implicitly. Here’s a quick example:

$string = '42';
$number = (int)$string;
// $number is now an integer (42)

Type Casting

Type casting is a straightforward approach to convert a string to a number:

$string = '42.3';
$intNumber = (int)$string;  // int(42)
$floatNumber = (float)$string;  // float(42.3)

Use caution with type casting as it can truncate values.

Using Functions

PHP offers functions like intval() and floatval() for conversions:

$string = '42 apples';
$number = intval($string);  // 42

This function reads the initial numeric part of the string, ignoring the rest.

For float conversion:

$string = '42.99 apples';
$number = floatval($string);  // 42.99

Mathematical Operations

Performing mathematical operations triggers type juggling:

$string = '42';
$number = $string * 1;  // int(42)
$string = '42.3';
$number = $string + 0;  // float(42.3)

Keep an eye out for non-numeric strings as they will equal to zero when used in a mathematical context.

String Parsing

PHP’s sscanf() function allows you to parse complex strings:

$string = '42 apples for $23';
sscanf($string, '%d %s', $number, $item);  // $number is 42

Locale-Aware Conversion

For strings with comma as a decimal separator:

setlocale(LC_NUMERIC, 'de_DE');
$string = '42,3';
$formatter = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$number = numfmt_parse($formatter, $string);  // 42.3

This ensures correct parsing according to locale conventions.

Using Regular Expressions

Regular expressions can be used to extract numbers from strings before converting:

$string = 'I have 42 apples';
if (preg_match('/(\d+)/', $string, $matches)) {
    $number = intval($matches[0]);
}  // $number is 42

This is particularly useful for strings with numbers embedded in text.

Caveats and Considerations

When converting strings, always check for potential losses in precision, considerations for locale-specific formats, and non-numeric string behavior.

Conclusion

To convert strings to numbers in PHP, various methods can be employed depending on the complexity of the task and string format. Understanding nuances is key in achieving accurate conversions without data loss.