0
0
PhpHow-ToBeginner · 2 min read

PHP How to Convert String to Int Easily

In PHP, convert a string to an integer by using (int)$string or the intval($string) function.
📋

Examples

Input"123"
Output123
Input"45abc"
Output45
Input"abc123"
Output0
🧠

How to Think About It

To convert a string to an integer in PHP, think about how PHP reads the string from left to right. If the string starts with numbers, PHP will convert those numbers into an integer. If it starts with letters, the result will be zero. You can use simple casting or a built-in function to do this.
📐

Algorithm

1
Take the input string.
2
Check if the string starts with numeric characters.
3
Convert the numeric part to an integer.
4
If no numeric part at the start, return zero.
5
Return the integer value.
💻

Code

php
<?php
$string1 = "123";
$string2 = "45abc";
$string3 = "abc123";

echo (int)$string1 . "\n"; // 123
echo intval($string2) . "\n"; // 45
echo (int)$string3 . "\n"; // 0
?>
Output
123 45 0
🔍

Dry Run

Let's trace converting the string "45abc" to an integer.

1

Input string

"45abc"

2

Check numeric start

Starts with "45" which is numeric

3

Convert to int

Result is 45

StepStringResult
1"45abc"N/A
2"45abc"Starts with 45
3"45abc"45
💡

Why This Works

Step 1: Casting with (int)

Using (int)$string tells PHP to treat the string as an integer, converting numeric characters at the start.

Step 2: Using intval() function

intval($string) does the same but is a function call, useful for clarity or when you want to specify base.

Step 3: Non-numeric strings

If the string does not start with numbers, the conversion results in zero because PHP finds no valid integer at the start.

🔄

Alternative Approaches

Using sscanf()
php
<?php
$string = "123abc";
sscanf($string, "%d", $number);
echo $number; // 123
?>
This extracts the integer from the start but requires more code and is less common.
Using filter_var() with FILTER_VALIDATE_INT
php
<?php
$string = "123";
$int = filter_var($string, FILTER_VALIDATE_INT);
echo $int; // 123
?>
This validates if the string is a valid integer but returns false if not, so it is stricter.

Complexity: O(1) time, O(1) space

Time Complexity

Conversion is done in constant time because PHP reads only the start of the string until it finds non-numeric characters.

Space Complexity

No extra memory is needed besides the integer variable, so space is constant.

Which Approach is Fastest?

Casting with (int) is fastest and simplest; functions like intval() add slight overhead but are still very efficient.

ApproachTimeSpaceBest For
(int) castingO(1)O(1)Simple and fast conversion
intval() functionO(1)O(1)Clear function call, supports base
sscanf()O(1)O(1)Extracting integer from formatted string
filter_var()O(1)O(1)Validating integer strings strictly
💡
Use (int)$string for quick and simple string to integer conversion in PHP.
⚠️
Trying to convert strings with letters at the start expecting a number, but PHP returns zero instead.