<p>How do I convert the value of a PHP variable to string?</p>

<p>I was looking for something better than concatenating with an empty string:</p>

<pre><code>$myText = $myVar . '';
</code></pre>

<p>Like the <code>ToString()</code> method in Java or .NET.</p>

[{'answer_id': 28101, 'author': 'Mark Biek', 'author_id': 305, 'author_profile': 'https://Stackoverflow.com/users/305', 'pm_score': 4, 'selected': False, 'text': '<p>Putting it in double quotes should work:</p>\n\n<pre><code>$myText = "$myVar";\n</code></pre>\n'}, {'answer_id': 28104, 'author': 'Joel Coehoorn', 'author_id': 3043, 'author_profile': 'https://Stackoverflow.com/users/3043', 'pm_score': 1, 'selected': False, 'text': "<p>You can always create a method named .ToString($in) that returns</p>\n\n<pre><code>$in . '';  \n</code></pre>\n"}, {'answer_id': 28108, 'author': 'Chris', 'author_id': 2134, 'author_profile': 'https://Stackoverflow.com/users/2134', 'pm_score': 5, 'selected': False, 'text': '<blockquote>\n  <p>How do I convert the value of a PHP\n  variable to string?</p>\n</blockquote>\n\n<p>A value can be converted to a string using the <a href="http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting" rel="nofollow noreferrer">(string) cast</a> or the <a href="http://ca.php.net/strval" rel="nofollow noreferrer">strval()</a> function. (Edit: As <a href="https://stackoverflow.com/users/2314/thomas-g-mayfield">Thomas</a> also stated).</p>\n\n<p>It also should be automatically casted for you when you use it as a string.</p>\n'}, {'answer_id': 28111, 'author': 'Tom Mayfield', 'author_id': 2314, 'author_profile': 'https://Stackoverflow.com/users/2314', 'pm_score': 11, 'selected': True, 'text': '<p>You can use the <a href="http://us3.php.net/manual/en/language.types.type-juggling.php" rel="noreferrer">casting operators</a>:</p>\n\n<pre><code>$myText = (string)$myVar;\n</code></pre>\n\n<p>There are more details for string casting and conversion in the <a href="http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting" rel="noreferrer">Strings section</a> of the PHP manual, including special handling for booleans and nulls.</p>\n'}, {'answer_id': 28115, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 1, 'selected': False, 'text': "<p>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).</p>\n"}, {'answer_id': 28119, 'author': 'Allain Lalonde', 'author_id': 2443, 'author_profile': 'https://Stackoverflow.com/users/2443', 'pm_score': 1, 'selected': False, 'text': '<p>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 <a href="http://dk1.php.net/printf" rel="nofollow noreferrer">printf</a> is your answer.</p>\n'}, {'answer_id': 28131, 'author': 'Ross', 'author_id': 2025, 'author_profile': 'https://Stackoverflow.com/users/2025', 'pm_score': 8, 'selected': False, 'text': '<p>This is done with typecasting:</p>\n\n<pre><code>$strvar = (string) $var; // Casts to string\necho $var; // Will cast to string implicitly\nvar_dump($var); // Will show the true type of the variable\n</code></pre>\n\n<p>In a class you can define what is output by using the magical method <a href="http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring" rel="noreferrer"><code>__toString</code></a>. An example is below:</p>\n\n<pre><code>class Bottles {\n    public function __toString()\n    {\n        return \'Ninety nine green bottles\';\n    }\n}\n\n$ex = new Bottles;\nvar_dump($ex, (string) $ex);\n// Returns: instance of Bottles and "Ninety nine green bottles"\n</code></pre>\n\n<p>Some more type casting examples:</p>\n\n<pre><code>$i = 1;\n\n// int 1\nvar_dump((int) $i);\n\n// bool true\nvar_dump((bool) $i);\n\n// string "1"\nvar_dump((string) 1);\n</code></pre>\n'}, {'answer_id': 28152, 'author': 'Michał Niedźwiedzki', 'author_id': 2169, 'author_profile': 'https://Stackoverflow.com/users/2169', 'pm_score': 4, 'selected': False, 'text': '<p>For primitives just use <code>(string)$var</code> or print this variable straight away. PHP is dynamically typed language and variable will be casted to string on the fly.</p>\n\n<p>If you want to convert objects to strings you will need to define <code>__toString()</code> method that returns string. This method is forbidden to throw exceptions.</p>\n'}, {'answer_id': 1936122, 'author': 'opensas', 'author_id': 47633, 'author_profile': 'https://Stackoverflow.com/users/47633', 'pm_score': 5, 'selected': False, 'text': '<p>You are looking for <a href="http://php.net/manual/en/function.strval.php" rel="noreferrer">strval</a>:</p>\n<blockquote>\n<h3><code>string strval ( mixed $var )</code></h3>\n<p>Get the string value of a variable.\nSee the documentation on string for\nmore information on converting to\nstring.</p>\n<p>This function performs no formatting\non the returned value. If you are\nlooking for a way to format a numeric\nvalue as a string, please see\nsprintf() or number_format().</p>\n</blockquote>\n'}, {'answer_id': 1991021, 'author': 'Joel Larson', 'author_id': 242230, 'author_profile': 'https://Stackoverflow.com/users/242230', 'pm_score': 6, 'selected': False, 'text': "<p>You can either use typecasting:</p>\n\n<pre><code>$var = (string)$varname;\n</code></pre>\n\n<p>or StringValue:</p>\n\n<pre><code>$var = strval($varname);\n</code></pre>\n\n<p>or SetType:</p>\n\n<pre><code>$success = settype($varname, 'string');\n// $varname itself becomes a string\n</code></pre>\n\n<p>They all work for the same thing in terms of Type-Juggling.</p>\n"}, {'answer_id': 3559247, 'author': 'Cedric', 'author_id': 278739, 'author_profile': 'https://Stackoverflow.com/users/278739', 'pm_score': 7, 'selected': False, 'text': '<p>Use <a href="https://www.php.net/manual/en/function.print-r.php" rel="nofollow noreferrer"><strong>print_r</strong></a>:</p>\n\n<pre><code>$myText = print_r($myVar,true);\n</code></pre>\n\n<p>You can also use it like: </p>\n\n<pre><code>$myText = print_r($myVar,true)."foo bar";\n</code></pre>\n\n<p>This will set <code>$myText</code> to a string, like:</p>\n\n<pre><code>array (\n  0 =&gt; \'11\',\n)foo bar\n</code></pre>\n\n<p>Use <a href="https://www.php.net/manual/en/function.var-export.php" rel="nofollow noreferrer"><strong>var_export</strong></a> to get a little bit more info (with types of variable,...):</p>\n\n<pre><code>$myText = var_export($myVar,true);\n</code></pre>\n'}, {'answer_id': 5219818, 'author': 'Justin Weeks', 'author_id': 598548, 'author_profile': 'https://Stackoverflow.com/users/598548', 'pm_score': 3, 'selected': False, 'text': '<p>Another option is to use the built in <a href="http://us3.php.net/manual/en/function.settype.php" rel="noreferrer">settype</a> function:</p>\n\n<pre><code>&lt;?php\n$foo = "5bar"; // string\n$bar = true;   // boolean\n\nsettype($foo, "integer"); // $foo is now 5   (integer)\nsettype($bar, "string");  // $bar is now "1" (string)\n?&gt;\n</code></pre>\n\n<p>This actually performs a conversion on the variable unlike typecasting and allows you to have a general way of converting to multiple types.</p>\n'}, {'answer_id': 6891412, 'author': 'Flak DiNenno', 'author_id': 589655, 'author_profile': 'https://Stackoverflow.com/users/589655', 'pm_score': 1, 'selected': False, 'text': '<p>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.</p>\n'}, {'answer_id': 10473070, 'author': 'Yauhen Yakimovich', 'author_id': 544463, 'author_profile': 'https://Stackoverflow.com/users/544463', 'pm_score': 3, 'selected': False, 'text': '<p>In addition to the answer given by Thomas G. Mayfield: </p>\n\n<p>If you follow the link to the string casting manual, there is a special case which is quite important to understand:</p>\n\n<p>(string) cast is preferable especially if your variable <strong>$a</strong> is an object, because PHP will follow the casting <a href="http://ch.php.net/manual/en/language.oop5.magic.php#object.tostring">protocol</a> according to its object model by calling <strong>__toString()</strong> magic method (if such is defined in the class of which $a is instantiated from).</p>\n\n<p>PHP does something similar to</p>\n\n<pre><code>function castToString($instance) \n{ \n    if (is_object($instance) &amp;&amp; method_exists($instance, \'__toString\')) {\n        return call_user_func_array(array($instance, \'__toString\'));\n    }\n}\n</code></pre>\n\n<p>The <em>(string)</em> 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).</p>\n'}, {'answer_id': 15794348, 'author': 'Archimedes Trajano', 'author_id': 242042, 'author_profile': 'https://Stackoverflow.com/users/242042', 'pm_score': 0, 'selected': False, 'text': '<p>For objects, you may not be able to use the cast operator. Instead, I use the <code>json_encode()</code> method.</p>\n\n<p>For example, the following will output contents to the error log:</p>\n\n<pre><code>error_log(json_encode($args));\n</code></pre>\n'}, {'answer_id': 20011937, 'author': 'DarthKotik', 'author_id': 2964871, 'author_profile': 'https://Stackoverflow.com/users/2964871', 'pm_score': 2, 'selected': False, 'text': '<p>The documentation says that you can also do:</p>\n\n<pre><code>$str = "$foo";\n</code></pre>\n\n<p>It\'s the same as cast, but I think it looks prettier.</p>\n\n<p>Source:</p>\n\n<ul>\n<li><a href="http://php.net/manual/ru/language.types.type-juggling.php" rel="nofollow">Russian</a>  </li>\n<li><a href="http://us3.php.net/manual/en/language.types.type-juggling.php" rel="nofollow">English</a></li>\n</ul>\n'}, {'answer_id': 22016653, 'author': 'mikikg', 'author_id': 783354, 'author_profile': 'https://Stackoverflow.com/users/783354', 'pm_score': 0, 'selected': False, 'text': '<p>Try this little strange, but working, approach to convert the textual part of stdClass to string type:</p>\n\n<pre><code>$my_std_obj_result = $SomeResponse-&gt;return-&gt;data; // Specific to object/implementation\n\n$my_string_result = implode ((array)$my_std_obj_result); // Do conversion\n</code></pre>\n'}, {'answer_id': 22028490, 'author': 'Daan', 'author_id': 987864, 'author_profile': 'https://Stackoverflow.com/users/987864', 'pm_score': 4, 'selected': False, 'text': '<p>I think it is worth mentioning that you can catch any output (like <code>print_r</code>, <code>var_dump</code>) in a variable by using output buffering:</p>\n\n<pre><code>&lt;?php\n    ob_start();\n    var_dump($someVar);\n    $result = ob_get_clean();\n?&gt;\n</code></pre>\n\n<p>Thanks to:\n<em><a href="https://stackoverflow.com/questions/139474/how-can-i-capture-the-result-of-var-dump-to-a-string/139491#139491">How can I capture the result of var_dump to a string?</a></em></p>\n'}, {'answer_id': 23732710, 'author': 'user1587439', 'author_id': 1587439, 'author_profile': 'https://Stackoverflow.com/users/1587439', 'pm_score': 3, 'selected': False, 'text': '<p>Some, if not all, of the methods in the previous answers fail when the intended string variable has a <em>leading zero</em>, for example, <em>077543</em>.</p>\n\n<p>An attempt to convert such a variable fails to get the intended string, because the variable is converted to <em>base 8 (octal)</em>.</p>\n\n<p>All these will make <code>$str</code> have a value of <em>32611</em>:</p>\n\n<pre><code>$no = 077543\n$str = (string)$no;\n$str = "$no";\n$str = print_r($no,true);\n$str = strval($no);\n$str = settype($no, "integer");\n</code></pre>\n'}, {'answer_id': 31942656, 'author': 'Aby W', 'author_id': 2802318, 'author_profile': 'https://Stackoverflow.com/users/2802318', 'pm_score': 1, 'selected': False, 'text': '<p>You can also use the <a href="http://php.net/manual/en/function.var-export.php" rel="nofollow noreferrer">var_export</a> PHP function.</p>\n'}, {'answer_id': 33391476, 'author': 'ling', 'author_id': 405042, 'author_profile': 'https://Stackoverflow.com/users/405042', 'pm_score': -1, 'selected': False, 'text': '<p>I use <a href="https://github.com/lingtalfi/VariableToString" rel="nofollow noreferrer">variableToString</a>. It handles every PHP type and is flexible (you can extend it if you want).</p>\n'}, {'answer_id': 37725483, 'author': 'Daniel Adenew', 'author_id': 2281472, 'author_profile': 'https://Stackoverflow.com/users/2281472', 'pm_score': 1, 'selected': False, 'text': '<pre><code>$parent_category_name = "new clothes &amp; shoes";\n\n// To make it to string option one\n$parent_category = strval($parent_category_name);\n\n// Or make it a string by concatenating it with \'new clothes &amp; shoes\'\n// It is useful for database queries\n$parent_category = "\'" . strval($parent_category_name) . "\'";\n</code></pre>\n'}, {'answer_id': 39259207, 'author': 'jimp', 'author_id': 791265, 'author_profile': 'https://Stackoverflow.com/users/791265', 'pm_score': 3, 'selected': False, 'text': '<p>As others have mentioned, objects need a <code>__toString</code> method to be cast to a string. An object that doesn\'t define that method can still produce a string representation using the <a href="http://php.net/manual/en/function.spl-object-hash.php" rel="nofollow noreferrer">spl_object_hash</a> function.</p>\n\n<blockquote>\n  <p>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.</p>\n</blockquote>\n\n<p>I have a base Object class with a <code>__toString</code> method that defaults to calling <code>md5(spl_object_hash($this))</code> to make the output clearly unique, since the output from spl_object_hash can look very similar between objects.</p>\n\n<p>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).</p>\n'}, {'answer_id': 53883743, 'author': 'Xanlantos', 'author_id': 4693430, 'author_profile': 'https://Stackoverflow.com/users/4693430', 'pm_score': 3, 'selected': False, 'text': '<p>I think this question is a bit misleading since,\ntoString() in Java isn\'t just a way to cast something to a String. That is what <a href="http://us3.php.net/manual/en/language.types.type-juggling.php" rel="nofollow noreferrer">casting</a> via (string) or String.valueOf() does, and it works as well in PHP.</p>\n\n<pre><code>// Java\nString myText = (string) myVar;\n\n// PHP\n$myText = (string) $myVar;\n</code></pre>\n\n<p>Note that this can be problematic as Java is type-safe (<a href="https://stackoverflow.com/questions/16815279/difference-between-casting-to-string-and-string-valueof">see here for more details</a>).</p>\n\n<p>But as I said, this is casting and therefore not the equivalent of Java\'s toString().</p>\n\n<p>toString in Java <strong>doesn\'t just cast an object to a String. It instead will give you the String representation</strong>. And that\'s what <a href="https://www.php.net/manual/en/language.oop5.magic.php#object.tostring" rel="nofollow noreferrer">__toString()</a> in PHP does.</p>\n\n<pre><code>// Java\nclass SomeClass{\n    public String toString(){\n        return "some string representation";\n    }\n}\n\n// PHP\nclass SomeClass{\n    public function __toString()\n    {\n        return "some string representation";\n    }\n}\n</code></pre>\n\n<p>And from the other side:</p>\n\n<pre><code>// Java\nnew SomeClass().toString(); // "Some string representation"\n\n// PHP\nstrval(new SomeClass); // "Some string representation"\n</code></pre>\n\n<p>What do I mean by "giving the String representation"?\nImagine a class for a library with millions of books.</p>\n\n<ul>\n<li>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 either.</li>\n<li>To String instead will give you the String representation, i.e., only the name of the library. This is shorter and therefore gives you less, but more important information.</li>\n</ul>\n\n<p>These are both valid approaches but with very different  goals, neither is a perfect solution for every case and you have to chose wisely which fits better for your needs.</p>\n\n<p><strong>Sure, there are even more options:</strong></p>\n\n<pre><code>$no = 421337  // A number in PHP\n$str = "$no"; // In PHP, stuff inside "" is calculated and variables are replaced\n$str = print_r($no, true); // Same as String.format();\n$str = settype($no, \'string\'); // Sets $no to the String Type\n$str = strval($no); // Get the string value of $no\n$str = $no . \'\'; // As you said concatenate an empty string works too\n</code></pre>\n\n<p>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 <a href="http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting" rel="nofollow noreferrer">PHP documentation</a> for more details.</p>\n'}, {'answer_id': 64322954, 'author': 'dılo sürücü', 'author_id': 5582655, 'author_profile': 'https://Stackoverflow.com/users/5582655', 'pm_score': 0, 'selected': False, 'text': '<p>__toString method or (string) cast</p>\n<pre class="lang-php prettyprint-override"><code>$string=(string)$variable;  //force make string \n</code></pre>\n<p>you can treat an object as a string</p>\n<pre class="lang-php prettyprint-override"><code>\nclass Foo\n{\n\n  public function __toString()\n  {\n     return &quot;foo&quot;;\n  }\n\n}\n\necho new Foo(); //foo\n</code></pre>\n<p>also, have another trick, ı assume ı  have int variable ı want to make string it</p>\n<pre class="lang-php prettyprint-override"><code>\n$string=\'\'.$intvariable;\n</code></pre>\n'}, {'answer_id': 72723752, 'author': 'JSON', 'author_id': 1246037, 'author_profile': 'https://Stackoverflow.com/users/1246037', 'pm_score': 0, 'selected': False, 'text': '<p>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 <code>$myText = $my_var .\'\';</code>  and  <code>$myText = (string)$my_var;</code> (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.</p>\n<p>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.</p>\n<p>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 <strong>specific to the object or data type</strong>. In that way the magic methods __toString() and __serialize()/__unserialize() may be the best comparison.</p>\n<p>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.</p>\n<p>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.</p>\n<p>These links my be helpful:</p>\n<p><a href="https://www.php.net/manual/en/language.types.type-juggling.php" rel="nofollow noreferrer">https://www.php.net/manual/en/language.types.type-juggling.php</a>\n<a href="https://www.php.net/manual/en/language.oop5.magic.php" rel="nofollow noreferrer">https://www.php.net/manual/en/language.oop5.magic.php</a></p>\n'}]
['https://Stackoverflow.com/questions/28098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2680/']