Use intval() when you need to converts a value to an integer, optionally using a base for numeric strings in a PHP application. The examples below show the actual operation and its limitations.
What Is intval() in PHP?
Converts a value to an integer, optionally using a base for numeric strings. The exact signature supported by your installation depends on its PHP version and enabled extensions.
Its syntax is:
intval(mixed $value, int $base = ...): int
Parameters and return value: The parameter types, optional arguments, references, and return type are shown in the signature above. Optional parameters are marked with an ellipsis in this reference signature.
Example 1: Basic Usage
<?php
echo intval("42");
Output:
42
Example 2: Different Input or Behavior
<?php
echo intval("FF",16);
Output:
255
Practical Example: Applying the Function
<?php
$submittedQuantity = "12"; $quantity = filter_var($submittedQuantity,FILTER_VALIDATE_INT); echo $quantity === false ? "Invalid" : "Quantity: " . $quantity;
Output:
Quantity: 12
Important Behavior and Edge Cases
intval() performs conversion, not input validation; malformed strings may become zero.
Comparison With Related Functions
| Approach | Difference |
|---|---|
intval() | Converts a value to an integer, optionally using a base for numeric strings. |
| Related operation | filter_var() with FILTER_VALIDATE_INT validates a complete integer representation. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring the function-specific limitation | intval() performs conversion, not input validation; malformed strings may become zero. |
| Confusing this function with a related operation | filter_var() with FILTER_VALIDATE_INT validates a complete integer representation. |
Key Takeaways
- Converts a value to an integer, optionally using a base for numeric strings.
- intval() performs conversion, not input validation; malformed strings may become zero.
- filter_var() with FILTER_VALIDATE_INT validates a complete integer representation.
Use intval() for the specific operation demonstrated above. Check its prerequisites and handle failure conditions before using it with production data.