PHP

PHP – Converting an integer to a string in PHP

  • There are few ways to change the type of a value from integer to string. In the following you’ll find three ways-

Method 1:

Applying type casting

In this method, to convert an integer to string, write (string) before the integer, and PHP will convert it to string type. See the following example-

Php Code
<?php
$intVal = 1812;
$strVal = (string)$intVal;
 
var_dump($strVal);
?>

Output:

string(4) “1812″

How it works:

Line 2 The variable $intVal contains the 1812 which is an integer.
Line 3 Here, we cast the type of the variable $intVal to string. And, after that, we store the value to $strVal variable.
Line 5 To test whether the type casting has been successful we use var_dump() function which displays type and value of the variable in the output.

Method 2:

Using strval() function

The strval() function will return the string value of a variable. See the following example-

Php Code
<?php
$intVal = 1812;
$strVal = strval($intVal);
 
var_dump($strVal);
?>

Output:

string(4) “1812″

How it works:

Line 2 The variable $intVal contains the 2566 which is a integer..
Line 3 The strval() function change the type of the $intVal variable to string, and stores in the $strVal variable.
Line 5 Here, we display the type and value of variable $strVal using var_dump() function. It shows in the outout that the variable is now a string type.

Method 3:

Surrounding quotes

One of the easy ways to convert an integer to string is to add quotes around the variable.
You can use either single or double quotes. See the following example

Php Code
<?php
$intVal = 1812;
$strVal = "$intVal";
 
var_dump($strVal);
?>

Output:

string(4) “1812″

READ  [Solved -7 Answers] CSS - Is the recommendation to include CSS before JavaScript invalid

About the author

Wikitechy Editor

Wikitechy Editor

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

Add Comment

Click here to post a comment

X