Convert Numbers to Strings?
In a string context, PHP will automatically convert any numeric value to a string. Here is a PHP script examples:
<?php
print(-1.3e3);
print("\n");
print(strlen
(
int("Price = $" . 99.99 . "\n");
p
p
rrint(1 . " + " . 2 . " = " . 1+2 . "\n");
print(1 . " + " . 2 . " = " . (1+2) . "\n");
print(1 . " + " . 2 . " = 3\n");
print("\n");
?
>
This script will print:
-1300
5
Price = $99.99
3
1 + 2 = 3
1 + 2 = 3
The print() function requires a string, so numeric value -1.3e3 is automatically converted to a string "-1300". The concatenation operator (.) also requires a string, so numeric value 99.99 is automatically converted to a string "99.99". Expression (1 . " + " . 2 . " = " . 1+2 . "\n") is a little bit interesting. The result is "3\n" because concatenation operations and addition operation are carried out from left to right. So when the addition operation is reached, we have "1 + 2 = 1"+2, which will cause the string to be converted to a value 1.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Convert Strings to Numbers?
In a numeric context, PHP will automatically convert any string to a numeric value. Strings will be converted into two types of numeric values, double floating number and integer, based on the following rules:
- The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).
- If the valid numeric data contains '.', 'e', or 'E', it will be converted to a double floating number. Otherwise, it will be converted to an integer.
Here is a PHP script example of converting some examples:
<?php
$foo = 1 + "10.5";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "-1.3e3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "bob-1.3e3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "bob3";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 1 + "10 Small Pigs";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = 4 + "10.2 Little Piggies";
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = "10.0 pigs " + 1;
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
$foo = "10.0 pigs " + 1.0;
echo "\$foo=$foo; type is " . gettype ($foo) . "\n";
?>
$foo=11.5; type is double
$foo=-1299; type is double
$foo=1; type is integer
$foo=1; type is integer
$foo=11; type is integer
$foo=14.2; type is double
$foo=11; type is double
$foo=11; type is double