Entry
How can I convert a numeric variable to a string, and viceversa (i.e. 10 to "10")?
Mar 23rd, 2001 18:50
Ben Udall, Carlos Martinez,
PHP is what's known as a loosely typed language, meaning variables can
change type (i.e. strings and numbers). For most purposes you don't
have to explictly convert from one type to another in PHP. For example:
$num = 123;
echo strlen($num);
This would produce, 3, even though $num is a number, PHP automatically
converted it to a string to get the string length. Likewise, strings
are automatically converted to numbers as needed:
$str = "4.8";
echo $str + 2;
As you might expect, the output would be "6.8". The string $str, was
converted to a number for the expression.
Here are a few more examples to give an idea of PHP's behaviour:
echo "hi" + 5; // Output is 5, non-numeric strings default to 0
echo "hi" + "bob"; // Output is 0, use "hi"."bob" to combine strings
echo "2" + "4"; // Output is 6, both strings are converted to
// numbers
echo "1abc" + 7; // Output is 8, if a number is the first thing in
// a string it's used instead of defaulting to 0
echo 3 + "a1"; // Output is 3, if a number isn't the first thing
// in a string, the string is converted to 0
PHP also provides a number of functions to explicitly get and set a
variable's type.
gettype($var) - Returns $var's type as a string.
settype($var, $type) - Sets $var to the type specified by the string,
$type.
Possible types are "boolean", "integer", "double", "string", "array",
"object", "resource", "user function" (PHP 3 only, deprecated)
and "unknown type".
Lastly, a few examples illustrating gettype() and settype():
$var = "1.00";
echo $var;
settype($var, "integer");
echo " ".$var; // Output: 1.00 1
$var = "1.005";
echo $var;
settype($var, "integer");
echo " ".$var; // Output: 1.005 1
$var = "1.005";
echo $var;
settype($var, "double");
echo " ".$var; // Output: 1.005 1.005
$var = 56;
echo gettype($var);
settype($var, "string");
echo " ".gettype($var); // Output: integer string
$var = 5.5;
echo gettype($var);
settype($var, "string");
echo " ".gettype($var); // Output: double string
$var = "hi";
echo $var;
settype($var, "integer");
echo " ".$var; // Output: hi 0
$var = "-56.7abc";
echo $var;
settype($var, "double");
echo " ".$var; // Output: -56.7abc -56.7
$var = "hi-45";
echo $var;
settype($var, "integer");
echo " ".$var; // Output: hi-45 0