Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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
  • + Share This
  • 🔖 Save To Your Account