PHP – Convert String to Int in PHP

How to Convert String to int in PHP Language?

Often, in PHP a number is input as a string. To use it for any mathematical operation, we have to convert the string to int. There are two ways to do this: manually convert the string to int in PHP or use built-in functions. So let’s solve it.

Manual Conversion

PHP Program Example

An example of converting a string to int in PHP without using library function.

Output:String To Int in PHP custom function.

Description of the program

The function char2decRadix converts char $c to decimal number in base $numberRadix.

The function string2int converts the $stringNumber to int number in base $numberRadix. The base range is from 2 till 36.

  1. Check if the string is not empty
  2. Check if a number is within a range [2, 36]
  3. Check the sign
  4. The String to int in base 10 conversion loop
  5. Returns the result, if the number is negative then change the sign of the number

Convert a string to int in PHP using the intval() function

(PHP 4, PHP 5, PHP 7)
intval() is a function that parses the $var which content is a integral number in the specified $base.



var – the scalar value being converted to an integer
base – the base to be used while parsing var.

if base is 0 (zero) or is not set, the base used is determined by the format of var:

  • 16 (hex) – when the string starts with “0x” (or “0X”);
  • 8 (octal) – if the string starts with “0”;
  • 10 (decimal) – in other cases.

Return Value

This function returns integer value of var on success, or 0 (zero) on failure. In case of empty arrays – returns 0 (zero), non-empty arrays – returns 1.
The maximum and minimum values depend on the system. For example 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So on such a system, intval('1000000000000') will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.
In case of strings the function will most likely return 0 (zero) although this depends on the leftmost characters of the string. The common rules of integer casting apply.


Output:String To Int in PHP intval() function.

The base parameter has no effect unless the var parameter is a string.

PHP – Wikipedia, the free encyclopedia
PHP syntax and semantics – Wikipedia, the free encyclopedia
PHP: intval – Manual
PHP Sandbox, test PHP online, PHP tester

Leave a Reply

Your email address will not be published. Required fields are marked *