• There are few ways to change the type of a value from integer to string. In the following you’ll find three ways-

Method 1:

Applying type casting

In this method, to convert an integer to string, write (string) before the integer, and PHP will convert it to string type. See the following example-

[pastacode lang=”php” manual=”%3C%3Fphp%0A%24intVal%20%3D%201812%3B%0A%24strVal%20%3D%20(string)%24intVal%3B%0A%20%0Avar_dump(%24strVal)%3B%0A%3F%3E%0A” message=”Php Code” highlight=”” provider=”manual”/] [ad type=”banner”]

Output:

string(4) “1812″

How it works:

Line 2 The variable $intVal contains the 1812 which is an integer.
Line 3 Here, we cast the type of the variable $intVal to string. And, after that, we store the value to $strVal variable.
Line 5 To test whether the type casting has been successful we use var_dump() function which displays type and value of the variable in the output.

Method 2:

Using strval() function

The strval() function will return the string value of a variable. See the following example-

[pastacode lang=”php” manual=”%3C%3Fphp%0A%24intVal%20%3D%201812%3B%0A%24strVal%20%3D%20strval(%24intVal)%3B%0A%20%0Avar_dump(%24strVal)%3B%0A%3F%3E%0A” message=”Php Code” highlight=”” provider=”manual”/] [ad type=”banner”]

Output:

string(4) “1812″

How it works:

Line 2 The variable $intVal contains the 2566 which is a integer..
Line 3 The strval() function change the type of the $intVal variable to string, and stores in the $strVal variable.
Line 5 Here, we display the type and value of variable $strVal using var_dump() function. It shows in the outout that the variable is now a string type.

Method 3:

Surrounding quotes

One of the easy ways to convert an integer to string is to add quotes around the variable.
You can use either single or double quotes. See the following example

[pastacode lang=”php” manual=”%3C%3Fphp%0A%24intVal%20%3D%201812%3B%0A%24strVal%20%3D%20%22%24intVal%22%3B%0A%20%0Avar_dump(%24strVal)%3B%0A%3F%3E%0A” message=”Php Code” highlight=”” provider=”manual”/] [ad type=”banner”]

Output:

string(4) “1812″

Categorized in: