Convert variable to string in PHP

→ Are you a new visitor? Please visit the page guidance for new visitors ←

Convert variable to string in PHP

PHP is a loosely typed language and assigns types to variables depending what is assigned to it. Sometimes you will want to transform a given variable into a string format and obtain a similar output with “ToString()" method in Java or .NET.

This could be done easily with one of the following methods:

1) Type casting ( Type Juggling )

From PHP official docs: “PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var$var becomes a string. If an integer value is then assigned to $var, it becomes an integer.”

Example:

2) String value

Get the string value of a variable.

Example:

2) SetType

Set the type of variable var to type.

Parameters:

var

The variable being converted.

type

Possibles values of type are:

  • “boolean” (or, since PHP 4.2.0, “bool”)
  • “integer” (or, since PHP 4.2.0, “int”)
  • “float” (only possible since PHP 4.2.0, for older versions use the deprecated variant “double”)
  • “string”
  • “array”
  • “object”
  • “null” (since PHP 4.2.0)

Example:

 

Request an article ←