How to Convert Integers to Strings and Strings to Integers in PHP

Posted on In Tutorial

Conversion from integer to string and from string to integer are common operations in most applications such as C++. PHP has its uniqueness in language and standard library design. In this post, we will check methods to convert integers to strings and vice versa.

Convert string to int in PHP

You can cast a string to int using the (int) cast directly. PHP provides a standard library function intval() to convert strings to integers. intval() can do the integer converting using specified base too.

One example usage is as follows.

$ php -a
Interactive mode enabled

php > $str = "8";
php > $n = (int)$str;
php > echo $n;
8
php > $m = intval($str);
php > echo $m;
8

Convert int to string in PHP

You can do casting too using (string) cast. PHP also provides at least 2 common functions for converting integers to strings: strval() and sprintf().

One example usage is as follows.

$ php -a
Interactive mode enabled

php > $n = 8;
php > $str = (string)$n;
php > echo $str;
8
php > echo strval($n);
8
php > echo sprintf("%d", $n);
8

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

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