0
0
PhpHow-ToBeginner · 2 min read

How to Convert int to String in PHP Easily

In PHP, you can convert an int to a string by using (string)$int or by concatenating the int with an empty string like $int . ''.
📋

Examples

Input123
Output"123"
Input0
Output"0"
Input-456
Output"-456"
🧠

How to Think About It

To convert an integer to a string in PHP, think of changing the number into text form. You can do this by telling PHP to treat the number as text using a cast or by joining it with an empty string, which forces PHP to convert it automatically.
📐

Algorithm

1
Get the integer value you want to convert.
2
Use a method to change the integer into a string, such as casting or concatenation.
3
Return or use the resulting string value.
💻

Code

php
<?php
$int = 123;
// Method 1: Casting
$str1 = (string)$int;
// Method 2: Concatenation
$str2 = $int . '';

print($str1 . "\n");
print($str2 . "\n");
?>
Output
123 123
🔍

Dry Run

Let's trace converting the integer 123 to a string using casting.

1

Start with integer

$int = 123

2

Cast integer to string

$str1 = (string)$int; // $str1 is now "123"

3

Print string

print($str1) outputs 123

StepVariableValue
1$int123
2$str1"123"
3Output123
💡

Why This Works

Step 1: Casting to string

Using (string)$int tells PHP to treat the integer as text, converting it directly.

Step 2: Concatenation forces conversion

Joining the integer with an empty string '' makes PHP convert the number to a string automatically.

🔄

Alternative Approaches

Using strval() function
php
<?php
$int = 123;
$str = strval($int);
print($str . "\n");
?>
This is a built-in function specifically for converting values to strings, making the code clear and readable.

Complexity: O(1) time, O(1) space

Time Complexity

Conversion is a simple operation done once, so it takes constant time.

Space Complexity

Only a small new string variable is created, so space used is constant.

Which Approach is Fastest?

Casting and concatenation are equally fast; using strval() is slightly more readable but similar in speed.

ApproachTimeSpaceBest For
Casting (string)$intO(1)O(1)Simple and clear conversion
Concatenation $int . ''O(1)O(1)Quick implicit conversion
strval() functionO(1)O(1)Readable and explicit conversion
💡
Use (string)$int for a quick and clear int to string conversion in PHP.
⚠️
Trying to convert int to string by just assigning without casting or concatenation, which keeps it as an int.