How to Convert a String to an Integer in PHP?

Problem:

You have a variable which contains a number as string(ex. “25”). Now, you want to convert the value to integer(ex. 25). This situation happens when a visitor submits a form which contains a numeric field(ex. zipcode), but, when you try to get the value in the next page, it shows as a string. So, you need to convert it to integer.

Solution:

You can convert a string to an integer in any of the following two ways-

Method 1: Applying type casting

In the type casting method, to cast the type of the variable from string to integer, write (int) before the string variable. See the following example-

<?php
$zipcode = "1000";
$zipcodeInt = (int)$zipcode;

var_dump($zipcodeInt);
?>

[wpdm_file id=137]

Output:
int(1000)

How it works:

Line 2 The variable $zipcode contains 1000 as a string.
Line 3 Here, we cast the type of the $zipcode from string to integer. And, we store the integer to $zipcodeInt variable.
Line 5 Here, we display the type and value of the variable $zipcodeInt. And, you see in the out that it is now an integer.

 

Method 2: Using intval() function

If a variable contains an integer value as string type(ex. “100”), you can get the integer value from the variable using intval() function. See it in action in the example below-

<?php
$zipcode = "2566";
$zipcode = intval($zipcode);

var_dump($zipcode);
?>

[wpdm_file id=138]

Output:
int(2566)

How it works:

Line 2 The variable $zipcode contains the number 2566 as string type data.
Line 3 Here, the intval() function returns integer value of the variable $zipcode which is 2566 and we store that integer value to $zipcodeInt.
Line 5 Here, we display the type and value of the variable $zipcodeInt. And, you see in the out that it is now an integer.