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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With