PHP Data Types

Values stored in a PHP variable or a PHP constant are stored as a specific type of data. PHP provides the following eight data types:

  • Integer: A whole number

  • Floating-point number (float): A numeric value with decimal digits

  • String: A series of characters

  • Boolean: A value that can be either true or false

  • NULL: A value that represents no value

  • Array: A group of values in one variable

  • Object: A structure created with a class

  • Resource: A reference that identifies a connection

Here are some things that you need to know about working with data types:

  • PHP determines the data type automatically. When writing PHP scripts, you don’t need to specify which data type you’re storing. The following two statements store different data types:

    $var1 = 123;
    $var2 = "123";

    The value for $var1 is stored as an integer. The value for $var2 is stored as a string because it’s enclosed in quotes.

  • PHP converts data types automatically when it needs to. For instance, if you add two variables, one containing an integer and one containing a float, PHP converts the integer to a float so that it can add the two.

  • You can determine the data type. Occasionally, you might want to store a value as a data type different than the data type PHP automatically stores. You can set the data type for a variable with a cast, as follows:

    $var3 = "222";
    $var4 = (int) $var3;

    This statement sets $var4 equal to the value in $var3, changing the value from a string to an integer. You can also cast using (float) or (string).

  • You can query the data type. You can find out which data type is stored in a variable with var_dump(). For instance, you can display a variable as follows:

    var_dump($var4);

    The output from this statement is the following:

int(222)
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com