PHP equivalent of .NET/Java's toString()


How do I convert the value of a PHP variable to string?

I was looking for something better than concatenating with an empty string:

$myText = $myVar . '';

Like the ToString() method in Java or .NET.

12/12/2018 4:08:22 PM

Accepted Answer

You can use the casting operators:

$myText = (string)$myVar;

There are more details for string casting and conversion in the Strings section of the PHP manual, including special handling for booleans and nulls.

8/26/2008 2:01:50 PM

Use print_r:

$myText = print_r($myVar,true);

You can also use it like:

$myText = print_r($myVar,true)."foo bar";

This will set $myText to a string, like:

array (
  0 => '11',
)foo bar

Use var_export to get a little bit more info (with types of variable,...):

$myText = var_export($myVar,true);

You can either use typecasting:

$var = (string)$varname;

or StringValue:

$var = strval($varname);

or SetType:

$success = settype($varname, 'string');
// $varname itself becomes a string

They all work for the same thing in terms of Type-Juggling.


How do I convert the value of a PHP variable to string?

A value can be converted to a string using the (string) cast or the strval() function. (Edit: As Thomas also stated).

It also should be automatically casted for you when you use it as a string.


You are looking for strval:

string strval ( mixed $var )

Get the string value of a variable. See the documentation on string for more information on converting to string.

This function performs no formatting on the returned value. If you are looking for a way to format a numeric value as a string, please see sprintf() or number_format().


For primitives just use (string)$var or print this variable straight away. PHP is dynamically typed language and variable will be casted to string on the fly.

If you want to convert objects to strings you will need to define __toString() method that returns string. This method is forbidden to throw exceptions.