Lesson 40 of 100
Types15 min5 checksPHP 8.5

Numeric Strings and Explicit Conversion

Learn which strings PHP 8.4 treats as numeric, why leading-numeric text is risky, and how to validate input before converting it.

01 · THE IDEAREAD → TRY → LEARN

Why numeric strings matter

Data from forms, query strings, CSV cells and JSON text often arrives as strings even when it represents a number. PHP will happily coerce strings in many places, but the rules differ depending on how much of the string looks like a number. If you convert first and ask questions later, bad input can quietly turn into a wrong total. The safer habit is to validate first, then convert, and to decide explicitly what happens to input that fails validation.

What counts as numeric

As of PHP 8.0, a string is numeric when it can be read as an integer or a float. Optional whitespace is allowed at the start and at the end, followed by an optional sign, digits, an optional decimal part and an optional exponent. That means "42", " 42", "42 ", "-0.5" and "4.2e1" are all numeric.

A leading-numeric string starts with a numeric part and then continues with other characters, such as "42abc". It is not numeric. Text such as "abc", an empty string, a lone "." or hexadecimal text like "0x2A" is non-numeric.

The function is_numeric() applies this definition to a value and returns a boolean, so it is the natural gatekeeper before a conversion.

Example
<?php
$samples = ["42", " 42", "42 ", "4.2e1", "42abc", "", "0x2A"];
$result = [];
foreach ($samples as $s) {
    $result[] = is_numeric($s);
}
echo json_encode($result), "\n";
Output
[true,true,true,true,false,false,false]

The output is a list of seven booleans: the first four samples are numeric, the last three are not.

Converting explicitly

Once a string passes is_numeric(), adding zero is a compact way to get a real number. An integer-looking string that fits the integer range becomes an int; anything with a decimal point or exponent becomes a float. An explicit cast such as (int) "12abc" is different: it reads the leading digits and silently ignores the rest, which is exactly why it must not be used as a validator.

Example
<?php
var_dump("10" + 0);
var_dump("10.5" + 0);
var_dump("1e2" + 0);
var_dump((int) "12abc");
Output
int(10)
float(10.5)
float(100)
int(12)

Notice that "1e2" becomes a float, not the integer 100. Scientific notation always produces a float. The manual also warns that text with an E between numbers can be read as an exponent, which affects loose comparisons such as "2E1" == "020".

Type declarations and failure

When a numeric string is passed to an int parameter in the default (non-strict) mode, PHP converts it. Surrounding whitespace is fine. A non-numeric string cannot be converted and raises a TypeError.

Example
<?php
function double(int $n): int {
    return $n * 2;
}

foreach ([" 12 ", "abc"] as $input) {
    try {
        echo double($input), "\n";
    } catch (TypeError $e) {
        echo "TypeError\n";
    }
}
Output
24
TypeError

In contexts that accept leading-numeric strings, PHP uses the leading number but raises a warning, so relying on that behavior makes logs noisy and hides data problems. Checking with is_numeric() first lets you handle bad values on your own terms instead of depending on context-specific rules.

Common pitfalls

  • Treating (int) $text as validation. It turns "abc" into 0 and "10 pigs" into 10.
  • Forgetting that an empty string and a string of spaces are not numeric.
  • Expecting "0x1A" to be read as hexadecimal; it is not numeric.
  • Using (int) on a decimal string and losing the fraction.

Exercise contract

Write sumNumericStrings(array $items): array. It receives a list of strings. Every numeric string is added to a running sum using its real numeric value (so "1.5" contributes a float). Every non-numeric string is not added, but is collected, in original order, in a skipped list. Return an associative array with the keys sum and skipped. An empty input gives a sum of 0 and an empty skipped list. The tests check the returned values, not printed output.

Recap

Numeric strings may have surrounding whitespace, a sign, decimals and an exponent. Leading-numeric text such as "42abc" is not numeric. Validate with is_numeric(), convert deliberately, and keep a clear policy for rejected input rather than letting casts hide it.

Before you start

Functions · Arrays · Types

You’ll practice
  • Validate numeric text before converting and preserve invalid-input behavior
  • Implement and test a deterministic PHP 8.4 function
Your task

Make sumNumericStrings() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.