Numbers to string and vice versa in PHP
How do I convert numbers to a string and vice versa开发者_如何学编程 in PHP?
1) Numbers to string: just use it like a string and it is a string, or explicitly cast.
$number = 1234;
echo "the number is $number";
$string = (string) $number;
$otherString = "$number";
2) Strings to number: use a c-style cast.
$string = "1234";
$int = (int) $string;
$float = (float) $string;
PHP is dynamically typed and will evaluate which scalar type to use depending on the context. You just have to be aware how this happens. See the PHP manual on
- Type Juggling
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string . If an integer value is then assigned to $var, it becomes an integer .
- String conversion to numbers
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer . In all other cases it will be evaluated as a float .
- Converting to string
A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo() or print() functions, or when a variable is compared to a string . The sections on Types and Type Juggling will make the following clearer. See also the settype() function.
There are functions like intval
and floatval
to parse number strings. And for number to string conversion, just use an explicit type casting using (string)
or implicitly via string concatenation.
精彩评论