PHP How to Convert String to Int Easily
(int)$string or the intval($string) function.Examples
How to Think About It
Algorithm
Code
<?php $string1 = "123"; $string2 = "45abc"; $string3 = "abc123"; echo (int)$string1 . "\n"; // 123 echo intval($string2) . "\n"; // 45 echo (int)$string3 . "\n"; // 0 ?>
Dry Run
Let's trace converting the string "45abc" to an integer.
Input string
"45abc"
Check numeric start
Starts with "45" which is numeric
Convert to int
Result is 45
| Step | String | Result |
|---|---|---|
| 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
<?php $string = "123abc"; sscanf($string, "%d", $number); echo $number; // 123 ?>
<?php $string = "123"; $int = filter_var($string, FILTER_VALIDATE_INT); echo $int; // 123 ?>
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| (int) casting | O(1) | O(1) | Simple and fast conversion |
| intval() function | O(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 |
(int)$string for quick and simple string to integer conversion in PHP.