This article demonstrates how to convert an integer or a float to a string in PHP.

1. Using Variable Interpolation

You can use variable interpolation to get the string representation of an integer or a float. PHP will parse the interpolated variables inside a double-quoted string, and replace them with their corresponding values. You can interpolate variables within a string literal with or without curly braces. Note that interpolating a variable into a single-quoted string will not work.

Download  Run Code

This results in below output:

0 => string(1) "0"
0.0 => string(1) "0"
1 => string(1) "1"
1.0 => string(1) "1"
-1 => string(2) "-1"
-1.0 => string(2) "-1"
1.5 => string(3) "1.5"
-1.5 => string(4) "-1.5"
1.5 => string(3) "1.5"
-1.5 => string(4) "-1.5"

 
You may also use the Heredoc syntax, which behaves like a double-quoted string but without double quotes. In PHP, this looks like:

Download  Run Code

2. Using strval() function

PHP has a built-in function strval() which converts a value to a string. This function returns the string value of the specified variable. It can be used to convert a scalar type to a string, as follows:

Download  Run Code

 
A more traditional way to convert a value to a string type is to explicitly cast it with the (string) cast. This works similarly to the strval() function. For example,

Download  Run Code

3. Using Concatenation operator

Finally, you can force a variable to be evaluated as a string type using the concatenation operator (.). It performs the concatenation of its right and left operands. The following example shows how to concatenate a numeric value with an empty string ("").

Download  Run Code

That’s all about converting an integer or a float to a string in PHP.