Question
I want to convert string values such as '3', '2.34', and '0.234343' into numeric values in PHP.
In JavaScript, we can use Number(). Is there a similar way to do this in PHP?
$values = ['2', '2.34', '0.3454545'];
Expected results:
| Input | Output |
|---|---|
'2' | 2 |
'2.34' | 2.34 |
'0.3454545' | 0.3454545 |
Short Answer
By the end of this page, you will understand how PHP converts strings to numbers, when to use (int) or (float), how PHP handles numeric strings automatically, and how to validate input safely before converting it.
Concept
In PHP, converting a string to a number is usually done with type casting or by letting PHP perform automatic type juggling.
A string like '2' can become an integer, and a string like '2.34' can become a float. The main tools are:
(int)for whole numbers(float)for decimal numbersis_numeric()to check whether a string can be interpreted as a number
Why this matters
In real applications, numbers often arrive as strings:
- form inputs from users
- query parameters in URLs
- JSON payloads from APIs
- CSV or database imports
Even if a value looks like a number, PHP may still treat it as a string until you convert or validate it. Understanding conversion helps you avoid bugs in calculations, comparisons, and validation logic.
Important behavior in PHP
PHP does not have a direct equivalent to JavaScript's Number() function with the exact same role and style. Instead, PHP commonly uses casting:
$intValue = (int) '2';
$floatValue = (float) '2.34';
If you want PHP to choose between integer and float based on the input, you typically inspect the string first and then cast accordingly.
Mental Model
Think of a string number as a label on a box.
'2'is a box labeled2'2.34'is a box labeled2.34
PHP can read the label and turn it into an actual numeric value you can calculate with. But you must tell PHP what kind of numeric box you want:
- an integer box for whole numbers
- a float box for decimals
If you choose the wrong box, you may lose information. For example, casting '2.34' to (int) gives 2, because integers do not keep decimal parts.
Syntax and Examples
Basic conversion with casting
$whole = (int) '2';
$decimal = (float) '2.34';
var_dump($whole); // int(2)
var_dump($decimal); // float(2.34)
Casting is the most common and direct way to convert strings to numbers in PHP.
Let PHP choose based on the string
If you want '2' to become 2 and '2.34' to become 2.34, you can inspect the value:
function toNumber(string $value): int|float {
return str_contains($value, '.') ? (float) $value : (int) $value;
}
var_dump(());
(());
(());
Step by Step Execution
Consider this example:
$value = '2.34';
if (is_numeric($value)) {
$number = str_contains($value, '.') ? (float) $value : (int) $value;
var_dump($number);
}
Step-by-step
-
$value = '2.34';- PHP stores the value as a string.
-
is_numeric($value)- PHP checks whether the string can be interpreted as a number.
'2.34'is numeric, so the condition is true.
-
str_contains($value, '.')- PHP checks whether the string contains a decimal point.
'2.34'does contain..
-
(float) $value
Real World Use Cases
String-to-number conversion appears in many common PHP tasks:
Form handling
$age = (int) $_POST['age'];
$price = (float) $_POST['price'];
HTML forms send values as strings, even when users type numbers.
Query parameters
$page = (int) $_GET['page'];
$discount = (float) $_GET['discount'];
Values from URLs arrive as strings and often need conversion.
API data
When reading JSON or external API data, a number may sometimes be delivered as a string:
$data = ['amount' => '19.99'];
$amount = (float) $data['amount'];
CSV import
$row = ['quantity' => , => ];
= () [];
= () [];
= * ;
Real Codebase Usage
In real projects, developers usually combine conversion with validation and clear intent.
Pattern: validate before converting
if (!is_numeric($input)) {
throw new InvalidArgumentException('Expected a numeric value.');
}
$number = (float) $input;
This prevents bad input from silently producing incorrect values.
Pattern: use integers for count-like values
$userId = (int) $request['user_id'];
$quantity = (int) $request['quantity'];
Use integers for IDs, counts, page numbers, and indexes.
Pattern: use floats for decimal values
$weight = (float) $request['weight'];
$rating = (float) $request['rating'];
Use floats when decimal precision is needed.
Pattern: guard clauses
Common Mistakes
1. Using (int) on decimal strings
Broken example:
$value = '2.34';
var_dump((int) $value); // int(2)
Problem:
(int)removes the decimal part.
Fix:
$value = '2.34';
var_dump((float) $value); // float(2.34)
2. Converting invalid strings without checking
Broken example:
$value = 'abc';
var_dump((int) $value); // int(0)
var_dump((float) $value); // float(0)
Problem:
- Invalid input may become
0, which can hide bugs.
Comparisons
| Approach | Example | Result | Best for |
|---|---|---|---|
| Integer cast | (int) '2' | 2 | Whole numbers only |
| Float cast | (float) '2.34' | 2.34 | Decimal values |
| Automatic conversion | '2.34' + 0 | 2.34 | Quick expressions, less explicit |
| Validation + cast | is_numeric($v) ? (float) $v : null | Safe conversion | User input and external data |
vs
Cheat Sheet
Quick conversion rules
(int) '2' // 2
(float) '2.34' // 2.34
(double) '2.34' // 2.34 (same as float)
Check before converting
is_numeric('2'); // true
is_numeric('2.34'); // true
is_numeric('abc'); // false
Convert based on content
$number = str_contains($value, '.') ? (float) $value : (int) $value;
Safe helper
function toNumber(string $value): || {
= ();
(!()) {
;
}
(, ) ? () : () ;
}
FAQ
Is there a Number() function in PHP like JavaScript?
Not exactly. In PHP, the usual approach is type casting with (int) or (float).
How do I convert a string to an integer in PHP?
Use:
$number = (int) '42';
How do I convert a string to a decimal number in PHP?
Use:
$number = (float) '3.14';
How can I check whether a string is numeric before converting it?
Use is_numeric():
is_numeric('123'); // true
is_numeric('12.5'); // true
is_numeric('abc'); // false
What happens if I cast '2.34' to int in PHP?
Mini Project
Description
Build a small PHP utility that reads an array of string values and converts only the valid numeric ones into PHP numbers. This demonstrates validation, integer vs float conversion, and how to safely ignore invalid input.
Goal
Create a function that accepts string values, converts valid numeric strings to int or float, and skips invalid entries.
Requirements
Requirement 1
Keep learning
Related questions
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.
Convert a PHP Object to an Associative Array
Learn how to convert a PHP object to an associative array, including quick methods, recursion, pitfalls, and practical examples.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.