Is there a way to convert an integer to a string in PHP?
14 Answers
You can use the strval()
function to convert a number to a string.
From a maintenance perspective its obvious what you are trying to do rather than some of the other more esoteric answers. Of course, it depends on your context.
$var = 5;
// Inline variable parsing
echo "I'd like {$var} waffles"; // = I'd like 5 waffles
// String concatenation
echo "I'd like ".$var." waffles"; // I'd like 5 waffles
// The two examples above have the same end value...
// ... And so do the two below
// Explicit cast
$items = (string)$var; // $items === "5";
// Function call
$items = strval($var); // $items === "5";
There's many ways to do this.
Two examples:
$str = (string) $int;
$str = "$int";
See the PHP Manual on Types Juggling for more.
There are a number of ways to "convert" an integer to a string in PHP.
The traditional computer science way would be to cast the variable as a string:
$int = 5;
$int_as_string = (string) $int;
echo $int . ' is a '. gettype($int) . "\n";
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
You could also take advantage of PHP's implicit type conversion and string interpolation:
$int = 5;
echo $int . ' is a '. gettype($int) . "\n";
$int_as_string = "$int";
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
$string_int = $int.'';
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
Finally, similar to the above, any function that accepts and returns a string could be used to convert and integer. Consider the following:
$int = 5;
echo $int . ' is a '. gettype($int) . "\n";
$int_as_string = trim($int);
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
I wouldn't recommend the final option, but I've seen code in the wild that relied on this behavior, so thought I'd pass it along.
As the answers here demonstrates nicely, yes, there are several ways. However, in PHP you rarely actually need to do that. The "dogmatic way" to write PHP is to rely on the language's loose typing system, which will transparently coerce the type as needed. For integer values, this is usually without trouble. You should be very careful with floating point values, though.
I would say it depends on the context. strval() or the casting operator (string) could be used. However, in most cases PHP will decide what's good for you if, for example, you use it with echo or printf...
One small note: die() needs a string and won't show any int :)
echo
it (used in so called string context). – hakrestrval()
doesn't change the$variable
internally neither. – hakre