Converting an integer to a string in PHP


Question

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

1
463
6/24/2019 9:41:28 PM

Accepted Answer

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";
726
11/5/2018 8:38:01 PM

There's many ways to do this.

Two examples:

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

See the PHP Manual on Types Juggling for more.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon