How To Convert string To int In PHP 5, 6 & 7

Many a time we come across numeric values in the form of text, in this article, we will explore how you convert a string to the type of integer.

PHP comes with some native functions that aid this conversion, let’s see them below –

Convert String To Int using intval()

This first example utilizes the intval() function

 

Code

$stringNumberToParse = "1";

// var_dump($stringNumberToParse); // string '1' (length=1)


// Convert to type integer
$parsedInt = intval($stringNumberToParse);


// var_dump(is_int($parsedInt)); // boolean true

// var_dump($parsedInt); // integer 1

echo $parsedInt;

 

Output

1

 

Note: The intval() function works with PHP 4, 5 and 7+.

 

Explained

  • First of all, we define  “1” as our string variable.
  • We use the var_dump functions just to print the characteristics of the variable, just for tutorial purposes, these can be removed.
  • We pass in the $stringNumberToParse value into the intval() function which subsequently will define the $parsedInt variable.

 

Convert By Type-Casting

We can type-cast using syntax such as (int)$variable, (float)$variable

 

PHP Code

$stringNumberToParse = "1";

//var_dump($stringNumberToParse); // string '1' (length=1)


// Convert the to type integer
$parsedInt = (int)$stringNumberToParse;


//var_dump(is_int($parsedInt)); // boolean true

//var_dump($parsedInt); // integer 1

echo $parsedInt;

 

Output

1

 

Note: The Type-Casting works with PHP 5 and 7+.

 

Explained

  • First of all, we define our string as “1”
  • We use the var_dump functions just to print the characteristics of the variable, just for tutorial purposes, these can be removed.
  • We use the (int) type casting syntax and hit the variable on the head with a hammer to convert and define the $parsedInt variable.

 

Further Reading –

Functions or techniques used in this article can be read about more on the PHP Docs –

SHARE ON

The Author: Dan Englishby

How To Convert string To int In PHP 5, 6 & 7
Posted in PHP

You May Also Like

Leave a Reply

Your email address will not be published.