Converting to and from Strings


Converting between string format and other formats is a common task on the Internet because the data passed from the browser to the server and back in text strings. To convert to a string, you can use the (string) cast or the strval function; here's what this might look like:

 <?php     $float = 1.2345;     echo (string) $float, "\n";     echo strval($float), "\n"; ?> 

A boolean trUE value is converted to the string "1", and the FALSE value is represented as "" (empty string). An integer or floating point number (float) is converted to a string representing the number with its digits (including the exponent part for floating point numbers). The value NULL is always converted to an empty string.

You can also convert a string to a number. The string will be treated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be treated as an integer.

PHP determines the numeric value of a string from the initial part of the string. If the string starts with numeric data, it will use that. Otherwise, the value will be 0 (zero). Valid numeric data consists of an optional sign (+ or -), followed by one or more digits (including a decimal point if you're using it) and an optional exponent (the exponent part is an 'e' or 'E', followed by one or more digits).

PHP will do the right thing if you start using a string in a numeric context, as when you start adding values together. Here are some examples to make all this clearer:

 <?php     $number = 1 + "14.5";     echo "$number\n";     $number = 1 + "-1.5e2";     echo "$number\n";     $text = "5.0";     $number = (float) $text;     echo $number / 2.0, "\n"; ?> 

And here's what you see when you run this script:

 15.5 -149 2.5 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net