Converting an integer to a string

03/21/2020 18:30:02

Is there a way to convert an integer to a string in PHP?

Verified Answer (771 Votes)

06/24/2009 04:43:58

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

// Explicit cast 
$items = (string)$var; // $items === "5";

// Function call
$items = strval($var); // $items === "5";
771

Answer #2 (86 Votes)

06/24/2009 04:42:57

There's many ways to do this.

Two examples:

 $str = (string) $int;
 $str = "$int";     

See the PHP Manual on Types Juggling for more.

86

Answer #3 (44 Votes)

06/24/2009 04:39:35
$foo = 5;

$foo = $foo . "";

Now $foo is a string.

But, you may want to get used to casting. As casting is the proper way to accomplish something of that sort:

$foo = 5;
$foo = (string)$foo;

Another way is to encapsulate in quotes:

$foo = 5;
$foo = "$foo"
44
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.