566

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.

DarkMukke
  • 2,469
  • 1
  • 23
  • 31
Antoine Aubry
  • 12,203
  • 10
  • 45
  • 74
  • 2
    I'd use `json_encode($myText)`. I've found that the suggested solutions `print_r` and `(string)var` work well for scalar values and simple objects. For complex variables, classes or objects if a complete `__toString()` is not defined I prefer the aforementioned `json_encode`. – Eric Kigathi Jan 12 '19 at 16:48

26 Answers26

789

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.

Tom Mayfield
  • 6,235
  • 2
  • 32
  • 43
  • 14
    `Object of class Foo could not be converted to string`. Is there a general solutions that can convert anything (arrays+objects+whatever) to a string? – ripper234 Jan 03 '13 at 15:42
  • 3
    This is the answer - http://stackoverflow.com/questions/28098/php-tostring-equivalent/3559247#3559247 – ripper234 Jan 03 '13 at 16:20
  • 2
    Note: this will give a PHP notice when used on arrays. – dave1010 Feb 12 '13 at 17:22
  • 29
    @MarkAmery He gave an answer that implicitly calls the `__toString()` "Magic Method", but didn't mention that at all. The user asked for an answer that was like the Java `toString()` method, and in PHP, that's the `__toString()` function. – Ky - Apr 09 '13 at 01:41
  • 1
    @Supuhstar Perhaps you disagree, but given the rest of the content of the question, I think it's much more likely that by 'like tostring()' the asker meant "the most idiomatic way of converting something to a string", rather than "a way of converting an object to a string specifically by using a method of that object". Sure, by the second interpretation, the right answer is `__toString()`, but by the former interpretation (which I think is more sensible), it's definitely either a cast or `strval()` - you obviously can't use __toString for a non-object like an integer, since they don't have it. – Mark Amery Apr 09 '13 at 23:39
  • I have to say you're both right. Judging by the upvotes on this comment and the other leader (which was edited later to include my answer and is now the most correct), people with both questions (a __toString() override, and string casting) come to this post for the answer. I've debated deleting this answer for some time, but it still receives a few votes every week, so clearly it's what some of the visitors want. – Tom Mayfield Apr 10 '13 at 23:04
  • @MarkAmery I kinda meant that if you want to specify what a string version of your object looks like, you're gonna have to specify a `__toString()` method. @ThomasG.Mayfield it can't hurt to edit it and add this fact. – Ky - Apr 11 '13 at 02:25
  • 2
    @Supuhstar Ah right, I finally understand where you're coming from. Sorry if I was being obtuse before. I agree that this is a relevant detail and it would be valuable to add it, perhaps separating the answer into 'Converting Primitives' and 'Converting Objects' sections with headers. – Mark Amery Apr 11 '13 at 09:32
  • or just do this ''.$yourvariable.'' – Brij Raj Singh - MSFT Oct 09 '13 at 11:53
312

This is done with typecasting:

$strvar = (string) $var; // Casts to string
echo $var; // Will cast to string implicitly
var_dump($var); // Will show the true type of the variable

In a class you can define what is output by using the magical method __toString. An example is below:

class Bottles {
    public function __toString()
    {
        return 'Ninety nine green bottles';
    }
}

$ex = new Bottles;
var_dump($ex, (string) $ex);
// Returns: instance of Bottles and "Ninety nine green bottles"

Some more type casting examples:

$i = 1;

// int 1
var_dump((int) $i);

// bool true
var_dump((bool) $i);

// string "1"
var_dump((string) 1);
Ross
  • 46,186
  • 39
  • 120
  • 173
126

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);
Community
  • 1
  • 1
Cedric
  • 5,135
  • 11
  • 42
  • 61
  • 2
    "when the return parameter is TRUE, [print_r] will return a string." As print_r is a nice way to print objects, arrays (and also numbers/strings), it is a good way to transform an object into a human-readable string. – Cedric Sep 01 '10 at 10:51
  • 1
    FYI newcomers, the `true` part is essential! I tried several methods of string conversion including `print_r` and was disappointed from all of them, and then I discovered the `true` parameter (read the documentation for why it works). – ripper234 Jan 03 '13 at 16:19
58

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.

Salman A
  • 262,204
  • 82
  • 430
  • 521
Joel Larson
  • 597
  • 4
  • 2
  • strval($varname) does the trick for me, especially when the value is returned as type "variant" and needs to be converted into string or int. – Milan Feb 26 '14 at 20:19
  • `strval()` is what I was lookigng for because I wanted to use it with `array_walk`. E.g. `$array = array('cat',$object); array_walk($array,'strval'); // $array = array('cat',$object->__toString)` – Buttle Butkus Apr 18 '14 at 23:31
34

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.

Community
  • 1
  • 1
Chris
  • 6,761
  • 6
  • 52
  • 67
28

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().

Community
  • 1
  • 1
opensas
  • 60,462
  • 79
  • 252
  • 386
  • 3
    This is actually very helpful because I wanted to convert all numbers to strings without using a custom callback. `$strings = array_map('strval', $my_numbers);` – Peter Chaula Jun 08 '17 at 12:47
  • This is the only answer that works with `array_map` and string callables in general. – Danon Oct 04 '18 at 15:07
18

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.

Michał Niedźwiedzki
  • 12,859
  • 7
  • 45
  • 47
15

Putting it in double quotes should work:

$myText = "$myVar";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Biek
  • 146,731
  • 54
  • 156
  • 201
11

I think it is worth mentioning that you can catch any output (like print_r, var_dump) in a variable by using output buffering:

<?php
    ob_start();
    var_dump($someVar);
    $result = ob_get_clean();
?>

Thanks to: How can I capture the result of var_dump to a string?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daan
  • 7,685
  • 5
  • 43
  • 52
  • 1
    it's worth mentioning that you don't need that with [print_r](http://us2.php.net//manual/en/function.print-r.php). Just use the override to return as a string. – ars265 Jun 17 '14 at 19:13
  • 1
    A better way would be to use `$result = var_export($someVar, true)` without ob. – Danon Oct 04 '18 at 15:07
7

In addition to the answer given by Thomas G. Mayfield:

If you follow the link to the string casting manual, there is a special case which is quite important to understand:

(string) cast is preferable especially if your variable $a is an object, because PHP will follow the casting protocol according to its object model by calling __toString() magic method (if such is defined in the class of which $a is instantiated from).

PHP does something similar to

function castToString($instance) 
{ 
    if (is_object($instance) && method_exists($instance, '__toString')) {
        return call_user_func_array(array($instance, '__toString'));
    }
}

The (string) casting operation is a recommended technique for PHP5+ programming making code more Object-Oriented. IMO this is a nice example of design similarity (difference) to other OOP languages like Java/C#/etc., i.e. in its own special PHP way (whenever it's for the good or for the worth).

Yauhen Yakimovich
  • 13,635
  • 8
  • 60
  • 67
7

As others have mentioned, objects need a __toString method to be cast to a string. An object that doesn't define that method can still produce a string representation using the spl_object_hash function.

This function returns a unique identifier for the object. This id can be used as a hash key for storing objects, or for identifying an object, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects.

I have a base Object class with a __toString method that defaults to calling md5(spl_object_hash($this)) to make the output clearly unique, since the output from spl_object_hash can look very similar between objects.

This is particularly helpful for debugging code where a variable initializes as an Object and later in the code it is suspected to have changed to a different Object. Simply echoing the variables to the log can reveal the change from the object hash (or not).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jimp
  • 16,999
  • 3
  • 27
  • 36
7

Another option is to use the built in settype function:

<?php
$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo is now 5   (integer)
settype($bar, "string");  // $bar is now "1" (string)
?>

This actually performs a conversion on the variable unlike typecasting and allows you to have a general way of converting to multiple types.

Justin Weeks
  • 368
  • 3
  • 5
7

I think this question is a bit misleading since, toString() in Java isn't just a way to cast something to a String. That is what casting via (string) does, and it works as well in PHP.

// Java
String myText = (string) myVar;

// PHP
$myText = (string) $myVar;

Note that this can be problematic as Java is type-safe (see here for more details).

But as I said, this is casting and therefore not the equivalent of Java's toString().

toString in Java doesn't just cast an object to a String. It instead will give you the String representation. And that's what __toString() in PHP does.

// Java
class SomeClass{
    public String toString(){
        return "some string representation";
    }
}

// PHP
class SomeClass{
    public function __toString()
    {
        return "some string representation";
    }
}

And from the other side:

// Java
new SomeClass().toString(); // "Some string representation"

// PHP
strval(new SomeClass); // "Some string representation"

What do I mean by "giving the String representation"? Imagine a class for a library with millions of books.

  • Casting that class to a String would (by default) convert the data, here all books, into a string so the String would be very long and most of the time not very useful.
  • To String instead will give you the String representation, i.e., only the library's name. This is shorter and therefore gives you less, but more important information.

These are both valid approaches but with very different goals, neither is a perfect solution for every case, and you have to choose wisely which fits your needs better.

Sure, there are even more options:

$no = 421337  // A number in PHP
$str = "$no"; // In PHP, the stuff inside "" is calculated and variables are replaced
$str = print_r($no, true); // Same as String.format();
$str = settype($no, 'string'); // Sets $no to the String Type
$str = strval($no); // Get the string value of $no
$str = $no . ''; // As you said concatenate an empty string works too

All of these methods will return a String, some of them using __toString internally and some others will fail on Objects. Take a look at the PHP documentation for more details.

Xanlantos
  • 887
  • 9
  • 18
6

Some, if not all, of the methods in the previous answers fail when the intended string variable has a leading zero, for example, 077543.

An attempt to convert such a variable fails to get the intended string, because the variable is converted to base 8 (octal).

All these will make $str have a value of 32611:

$no = 077543
$str = (string)$no;
$str = "$no";
$str = print_r($no,true);
$str = strval($no);
$str = settype($no, "integer");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1587439
  • 1,637
  • 1
  • 12
  • 8
  • 1
    This is PICNIC (problem in chair, not in computer) as [nothing fails here](https://stackoverflow.com/a/2496008)! `print 077543;` outputs `32611`, so this is the correct string value of `$no`. Nobody expects that `(string)+1` returns the string `+1` (it correctly returns `1`) nor that `$no = 1+1; print (string)$no;` outputs `1+1`. Notes: (1) Same for hex (`$no=0xff;`) as well. (2) You can get back the octal value with `'0'.decoct($no);` (3) `$no="077543";` keeps the leading `0`, "077543"+1` gives `77544` while `077543+1` (correctly) gives `32612`. (PS: not downvoted, as this err is common) – Tino Aug 31 '17 at 06:45
3

The documentation says that you can also do:

$str = "$foo";

It's the same as cast, but I think it looks prettier.

Source:

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DarthKotik
  • 43
  • 4
1

You can always create a method named .ToString($in) that returns

$in . '';  
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
1

If you're converting anything other than simple types like integers or booleans, you'd need to write your own function/method for the type that you're trying to convert, otherwise PHP will just print the type (such as array, GoogleSniffer, or Bidet).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brian Warshaw
  • 22,657
  • 9
  • 53
  • 72
1

PHP is dynamically typed, so like Chris Fournier said, "If you use it like a string it becomes a string". If you're looking for more control over the format of the string then printf is your answer.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Allain Lalonde
  • 91,574
  • 70
  • 187
  • 238
1

You can also use the var_export PHP function.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aby W
  • 217
  • 4
  • 12
1
$parent_category_name = "new clothes & shoes";

// To make it to string option one
$parent_category = strval($parent_category_name);

// Or make it a string by concatenating it with 'new clothes & shoes'
// It is useful for database queries
$parent_category = "'" . strval($parent_category_name) . "'";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Develop4Life
  • 7,581
  • 8
  • 58
  • 76
  • Downvoted, as I really have no idea what you want to tell us. Using `strval()` on strings is just a complete waste of time. – Tino Aug 31 '17 at 06:21
  • dude the thing is assume you recived a string value = when its repersented it is going to be "the string". But , when you wanted to display that in javascript you need to make it 'stringx'' – Develop4Life Sep 04 '17 at 07:45
  • **This is extremely dangerous** (not to say: plain wrong). Please have a look at https://stackoverflow.com/q/168214 or https://stackoverflow.com/q/23740548 to understand how to safely pass something from PHP to JS! (Sorry for being a bit offtopic: Passing a PHP var to JS was not part of the question.) – Tino Sep 07 '17 at 09:52
1

Double quotes should work too... it should create a string, then it should APPEND/INSERT the casted STRING value of $myVar in between 2 empty strings.

Flak DiNenno
  • 2,193
  • 4
  • 30
  • 57
0

For objects, you may not be able to use the cast operator. Instead, I use the json_encode() method.

For example, the following will output contents to the error log:

error_log(json_encode($args));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265
0

Try this little strange, but working, approach to convert the textual part of stdClass to string type:

$my_std_obj_result = $SomeResponse->return->data; // Specific to object/implementation

$my_string_result = implode ((array)$my_std_obj_result); // Do conversion
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mikikg
  • 1,488
  • 1
  • 11
  • 23
0

__toString method or (string) cast

$string=(string)$variable;  //force make string 

you can treat an object as a string


class Foo
{

  public function __toString()
  {
     return "foo";
  }

}

echo new Foo(); //foo

also, have another trick, ı assume ı have int variable ı want to make string it


$string=''.$intvariable;
dılo sürücü
  • 3,821
  • 1
  • 26
  • 28
0

This can be difficult in PHP because of the way data types are handled internally. Assuming that you don't mean complex types such as objects or resources, generic casting to strings may still result in incorrect conversion. In some cases pack/unpack may even be required, and then you still have the possibility of problems with string encoding. I know this might sound like a stretch but these are the type of cases where standard type juggling such as $myText = $my_var .''; and $myText = (string)$my_var; (and similar) may not work. Otherwise I would suggest a generic cast, or using serialize() or json_encode(), but again it depends on what you plan on doing with the string.

The primary difference is that Java and .NET have better facilities with handling binary data and primitive types, and converting to/from specific types and then to string from there, even if a specific case is abstracted away from the user. It's a different story with PHP where even handling hex can leave you scratching your head until you get the hang of it.

I can't think of a better way to answer this which is comparable to Java/.NET where _toString() and such methods are usually implemented in a way that's specific to the object or data type. In that way the magic methods __toString() and __serialize()/__unserialize() may be the best comparison.

Also keep in mind that PHP doesn't have the same concepts of primitive data types. In essence every data type in PHP can be considered an object, and their internal handlers try to make them somewhat universal, even if it means loosing accuracy such as when converting a float to int. You can't deal with types as you can in Java unless your working with their zvals within a native extension.

While PHP userspace doesn't define int, char, bool, or float as an objects, everything is stored in a zval structure which is as close to an object that you can find in C, with generic functions for handling the data within the zval. Every possible way to access data within PHP goes down to the zval structure and the way the zend vm allows you to handles them without converting them to native types and structures. With Java types you have finer grained access to their data and more ways to to manipulate them, but also greater complexity, hence the strong type vs weak type argument.

These links my be helpful:

https://www.php.net/manual/en/language.types.type-juggling.php https://www.php.net/manual/en/language.oop5.magic.php

JSON
  • 1,819
  • 20
  • 27
-1

I use variableToString. It handles every PHP type and is flexible (you can extend it if you want).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ling
  • 9,545
  • 4
  • 52
  • 49