PHP example

How to convert a string to a number in PHP

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

For input you don't control, use filter_var($s, FILTER_VALIDATE_INT) (or FILTER_VALIDATE_FLOAT): it returns the number, or false when the whole string isn't one. For a value you already trust, cast it: (int) $s, (float) $s or intval($s). Casts never fail, so (int) "12abc" is 12 and (int) "abc" is 0. The other way, (string) $n or strval($n) turns a number into a string.

PHP converts between strings and numbers on its own in many places, which is why the question is less "how" than "what happens with bad input". A cast reads as many digits as it can and silently gives 0 for the rest, filter_var rejects anything that isn't a whole number, and arithmetic on a non-numeric string has thrown a TypeError since PHP 8. The sections below cover validating, casting (including hex and other bases), the PHP 8 numeric-string rules, strict_types, turning a number back into a string, and parsing "true" and "false" into a boolean, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Validate with filter_varRecommended

filter_var with FILTER_VALIDATE_INT checks that the entire string is an integer and returns it as an int. Anything else, including "12abc", "3.99" and the empty string, gives false. Because "0" is valid and returns 0, test the result with === false, never with !$n. FILTER_VALIDATE_FLOAT does the same for decimals, and the options array adds a range check, so one call parses and validates a form field, a query string value or a line from a file.

validate.php
<?php

// The int, or false when the whole string is not an integer
$inputs = ['42', ' 42 ', '-7', '0', '12abc', 'abc', '3.99', '1e3', ''];
foreach ($inputs as $s) {
    $n = filter_var($s, FILTER_VALIDATE_INT);
    printf("%-8s -> %s\n", var_export($s, true), var_export($n, true));
}

// 0 is a valid result, so compare with === false
$n = filter_var('0', FILTER_VALIDATE_INT);
echo $n === false ? "not a number\n" : "got $n\n";

// Floats work the same; thousands separators need a flag
var_dump(filter_var('3.99', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1e3', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1,234.56', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1,234.56', FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND));

// A range check, and null instead of false on failure
$age = filter_var('150', FILTER_VALIDATE_INT, [
    'options' => ['min_range' => 0, 'max_range' => 120],
    'flags' => FILTER_NULL_ON_FAILURE,
]);
var_dump($age);

// PHP 8.5+: throw instead of returning false
try {
    filter_var('12abc', FILTER_VALIDATE_INT, FILTER_THROW_ON_FAILURE);
} catch (Filter\FilterFailedException $e) {
    echo $e->getMessage(), "\n";
}

Output

Surrounding spaces are trimmed, so ' 42 ' gives 42, but '12abc', '3.99' and '1e3' are all false for an int. The float filter accepts 1e3 as float(1000), and '1,234.56' only passes with FILTER_FLAG_ALLOW_THOUSAND. 150 is outside the 0 to 120 range, so the result is NULL. On PHP 8.5 and later, FILTER_THROW_ON_FAILURE throws a Filter\FilterFailedException instead; on older versions, check for false.

2(int), (float), intval and floatval

A cast never fails. (int) and intval() skip leading whitespace, read as many characters as form a number, and ignore the rest; if there is no number at the start, the result is 0. (float) and floatval() do the same for decimals. That makes them the right tool for values you have already checked (a database column, a validated field) and the wrong one for raw input, where "abc" and "0" look the same. intval also takes a base: 16 for hex, 2 for binary, or 0 to let a 0x, 0b or leading 0 decide.

casts.php
<?php

$inputs = ['42', ' 42', '12abc', 'abc', '1e3', '1,234.56', '3.99', '0x1A'];
foreach ($inputs as $s) {
    printf(
        "%-11s (int) %-5s (float) %s\n",
        var_export($s, true),
        var_export((int) $s, true),
        var_export((float) $s, true),
    );
}

// intval and floatval are the same as the casts in base 10
var_dump(intval('42'), floatval('3.99'));

// intval with a base
var_dump(intval('ff', 16));
var_dump(intval('0x1A', 16));
var_dump(intval('101', 2));
var_dump(intval('0x1A', 0));
var_dump(intval('012', 0));
var_dump(intval('012'));

// Too big for an int: the cast clamps, arithmetic switches to float
var_dump((int) '9999999999999999999');
var_dump((float) '9999999999999999999');
var_dump(PHP_INT_MAX + 1);

Output

'12abc' gives 12, 'abc' gives 0, and '1,234.56' gives 1 because the comma stops the read; strip it first with str_replace(',', '', $s). (int) '3.99' truncates to 3; it does not round. A 0x string casts to 0, so use intval($s, 16) or hexdec. With base 0, '012' is octal and gives 10, while the default base 10 gives 12. A string too big for a 64-bit int is clamped to PHP_INT_MAX, and PHP_INT_MAX + 1 becomes a float, which has lost the last digits.

3is_numeric and numeric strings in arithmetic

You often don't convert at all: PHP turns a numeric string into a number when you use it with +, * and the other arithmetic operators. is_numeric tells you whether that is safe: it is true for an integer, a decimal or an exponent, with optional whitespace around it. PHP 8 made the rules stricter. A string that only starts with a number now raises a Warning, a string with no number throws a TypeError, and comparing "12abc" == 12 is false. This example stops on purpose at the error you will see.

numeric.php
<?php

foreach (['42', ' 42 ', '-3.5', '1e3', '.5', '12abc', '0x1A', ''] as $s) {
    printf("is_numeric(%s) = %s\n", var_export($s, true),
        var_export(is_numeric($s), true));
}

// Numeric strings work in arithmetic
var_dump('10' + 5);
var_dump('1.5' + 1);
var_dump('10' * '2');

// PHP 8 compares a non-numeric string as a string
var_dump('12abc' == 12);
var_dump('abc' == 0);

// A leading number works, with a Warning on stderr
var_dump('12abc' + 1);

// No number at all: TypeError, and the script stops here
var_dump('abc' + 1);
echo "not reached\n";

Output

'12abc' + 1 still gives int(13), but stderr shows Warning: A non-numeric value encountered. 'abc' + 1 ends the script with Fatal error: Uncaught TypeError: Unsupported operand types: string + int, so not reached never prints. On PHP 7 the same line gave a warning and 1, and 'abc' == 0 was true, so code that relied on that breaks on PHP 8. Check with is_numeric or filter_var before doing math on input.

4Type declarations and strict_types

When a function declares an int parameter, PHP by default converts a numeric string for you: double('5') works. With declare(strict_types=1); as the first statement of a file, calls made from that file must pass an actual int, and a string throws a TypeError. That is the point of strict mode: the conversion happens once, explicitly, where the string enters your code. It applies to function arguments and return values only; '5' + 1 still works.

strict.php
<?php

declare(strict_types=1);

function double(int $n): int
{
    return $n * 2;
}

try {
    echo double('5'), "\n";
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

// Convert at the edge, then pass a real int
$input = '5';
$n = filter_var($input, FILTER_VALIDATE_INT);
if ($n !== false) {
    echo double($n), "\n";
}

// Operators are not affected by strict_types
var_dump('5' + 1);

Output

In strict mode the call fails with double(): Argument #1 ($n) must be of type int, string given. Without the declare line, double('5') returns 10, double('abc') and double('12abc') throw the same TypeError, and double('5.5') returns 10 with Deprecated: Implicit conversion from float-string "5.5" to int loses precision. The validated value from filter_var is a real int, so it passes in both modes.

5A number to a string

Going the other way is simpler, because it can't fail. (string) $n, strval($n), "$n" and $n . '' all give the same string, and echo or the . operator convert for you, so you rarely need an explicit step. Floats are where it gets interesting: echo and (string) round to 14 significant digits (the precision setting), while var_dump and json_encode print the shortest form that reads back exactly. To control the format, use number_format or sprintf.

to_string.php
<?php

$n = 42;

var_dump((string) $n);
var_dump(strval($n));
var_dump("$n");
var_dump($n . '');

// Usually PHP converts for you
echo 'Order #' . $n . " has {$n} items\n";

// Floats: echo rounds to 14 digits, var_dump and JSON do not
$sum = 0.1 + 0.2;
echo $sum, "\n";
var_dump($sum);
echo json_encode($sum), "\n";

// Whole floats drop the .0; big ones switch to E notation
echo 7.0, ' ', 1e15, ' ', PHP_INT_MAX + 1, "\n";

// Choose the format yourself
echo number_format($sum, 2), "\n";
echo number_format(1234567.891, 2), "\n";
echo sprintf('%.2f', $sum), ' ', sprintf('%05d', $n), "\n";

Output

The same 0.1 + 0.2 prints 0.3 with echo and 0.30000000000000004 with var_dump and json_encode: the value is the same, only the rounding differs. 7.0 echoes as 7, and 1e15 as 1.0E+15, because 16 digits are more than the 14 that echo shows. number_format($sum, 2) gives 0.30, and number_format(1234567.891, 2) adds the thousands separators: 1,234,567.89. For more on fixed decimals and leading zeros, see rounding to 2 decimal places.

6A string to a boolean

(bool) doesn't read the words in a string. Only the empty string and "0" are false; every other string, including "false", "no" and "0.0", is true. To parse a setting, a checkbox or an environment variable, use filter_var with FILTER_VALIDATE_BOOLEAN. It understands true/false, 1/0, yes/no and on/off in any case, and with FILTER_NULL_ON_FAILURE it returns null for anything else instead of false.

to_bool.php
<?php

// A cast is true for every string except "" and "0"
foreach (['false', 'no', '0.0', ' ', '0', ''] as $s) {
    printf("(bool) %-7s = %s\n", var_export($s, true),
        var_export((bool) $s, true));
}

// filter_var reads the words; null means "not a boolean"
foreach (['true', 'FALSE', 'yes', 'off', '1', '0', 'maybe', ''] as $s) {
    $b = filter_var($s, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
    printf("%-7s -> %s\n", var_export($s, true), var_export($b, true));
}

// And back: true is "1", false is ""
var_dump((string) true, (string) false);
$debug = false;
echo 'debug: ', $debug ? 'true' : 'false', "\n";
echo json_encode(['debug' => $debug]), "\n";

Output

(bool) 'false' is true, which is the bug behind most "my setting is always on" reports. filter_var maps 'FALSE' and 'off' to false and 'maybe' to NULL. One catch: the empty string gives false, not NULL, so check for a missing value separately if that matters. Casting a bool to a string gives "1" or an empty string, so print it with a ternary or json_encode, which writes false.

7Which should you use?

Method"12abc" givesOn bad inputBest for
filter_var($s, FILTER_VALIDATE_INT)falsefalse or nullUser input, files, query strings
filter_var($s, FILTER_VALIDATE_FLOAT)falsefalse or nullDecimal input, exponents
(int) $s / intval($s)120, no errorValues you already validated
(float) $s / floatval($s)12.00.0, no errorTrusted decimal values
intval($s, 16) / intval($s, 0)76476 (valid hex)0, no errorHex, binary and octal text
$s + 012, plus a WarningTypeErrorAvoid as a conversion

Frequently asked questions

How do I convert a string to an int in PHP?

Cast it with (int) $s or call intval($s); both return 42 for "42". If the string comes from a user, use filter_var($s, FILTER_VALIDATE_INT) instead, which returns false for input like "12abc" or "abc" rather than quietly giving 12 or 0.

What is the difference between (int) and intval()?

In base 10 they give the same result: (int) '12abc' and intval('12abc') are both 12. intval takes a second argument for the base, so intval('ff', 16) is 255 and intval('0x1A', 0) reads the prefix and gives 26. (int) is a language construct and a little faster; intval can be passed as a callback, as in array_map('intval', $parts).

How do I check if a string is a number in PHP?

is_numeric($s) is true for integers, decimals and exponents such as "42", "-3.5" and "1e3". For an integer only, use filter_var($s, FILTER_VALIDATE_INT) !== false. ctype_digit($s) checks for digits only, so it is false for "-42" and for the empty string.

Why does (bool) "false" return true?

A cast to bool only treats "" and "0" as false; every other string is true, whatever it says. Use filter_var($s, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE), which returns false for "false", "no", "off" and "0", true for "true", "yes", "on" and "1", and null for anything else.

What does "A non-numeric value encountered" mean?

PHP 8 shows Warning: A non-numeric value encountered when you do math with a string that starts with a number but has more after it, such as '12abc' + 1 (the result is 13). A string with no number at all, such as 'abc' + 1, throws TypeError: Unsupported operand types: string + int. Validate with filter_var or is_numeric before the arithmetic.

How do I convert "1,234.56" to a float?

A cast stops at the comma and gives 1.0. Use filter_var($s, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND), which returns 1234.56, or remove the commas first: (float) str_replace(',', '', $s). Locale-aware parsing (such as "1.234,56") needs NumberFormatter::parse from the intl extension, which is not loaded on this page's PHP.

How do I convert a hex or binary string to a number?

Use hexdec('1A') (26), bindec('101') (5) and octdec('17') (15), or intval($s, 16) and intval($s, 2). A plain cast does not read prefixes: (int) '0x1A' is 0. The other way, dechex(255) is "ff" and decbin(10) is "1010".

Run it yourself

Open any of these in the full PHP editor to tweak, run and share.

PHP playground