In PHP, working with different data types is a regular part of programming. One common task is converting an integer to a string. This tutorial walks you through various ways to perform this conversion — from simple to advanced — so that you're not just memorizing methods, but truly understanding how and why they work.
Before diving into methods, let’s understand the why. You may want to convert an integer to a string in PHP when:
strval()
FunctionThe strval()
function is the most straightforward way to convert an integer into a string in PHP.
<?php
$number = 123;
$string = strval($number);
echo gettype($string);
echo "\n";
echo $string;
?>
string
123
strval()
directly converts the integer to a string. gettype()
confirms the type after conversion. This method is clean, readable, and preferred for general use.
PHP also supports manual or explicit type casting. You can force a type conversion using (string)
.
<?php
$number = 456;
$string = (string)$number;
echo gettype($string);
echo "\n";
echo $string;
?>
string
456
This method is handy when you want complete control over type conversion. The syntax may seem technical but it's widely used by experienced PHP developers.
You can force PHP to treat an integer as a string by appending it to an empty string using the dot operator (.
).
<?php
$number = 789;
$string = $number . "";
echo gettype($string);
echo "\n";
echo $string;
?>
string
789
This is a creative and idiomatic way of converting an integer to a string. While it may look like a hack, it's perfectly valid and commonly used in templating and display logic.
sprintf()
Functionsprintf()
offers formatted output, and can be used to convert integers into strings with specific formatting.
<?php
$number = 100;
$string = sprintf("%d", $number);
echo gettype($string);
echo "\n";
echo $string;
?>
string
100
sprintf()
is especially useful when you need to format numbers before converting them. You can control padding, decimal places, and other format rules.
json_encode()
Though it’s not the primary use-case, json_encode()
can convert integers to strings in a JSON-safe way.
<?php
$number = 321;
$string = json_encode($number);
echo gettype($string);
echo "\n";
echo $string;
?>
string
321
While json_encode()
is typically used for arrays and objects, it does convert individual values too. This approach is useful when dealing with data interchange formats like JSON.
strval()
or type casting for readability and simplicity.sprintf()
when formatting is required.<?php
$input = 200;
if (is_int($input)) {
$string = strval($input);
echo "Converted: " . $string;
} else {
echo "Input is not an integer.";
}
?>
Converted: 200
Whether you need clean code, formatting control, or inline tricks — PHP gives you multiple ways to convert integers to strings.
You can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.