Arlen Beiler
Arlen Beiler

Reputation: 15866

Numbers to string and vice versa in PHP

How do I convert numbers to a string and vice versa in PHP?

Upvotes: 0

Views: 810

Answers (3)

Gordon
Gordon

Reputation: 316939

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

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 .

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 .

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.

Upvotes: 2

grossvogel
grossvogel

Reputation: 6782

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; 

Upvotes: 2

Gumbo
Gumbo

Reputation: 655129

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.

Upvotes: 0

Related Questions