PHP 5 Data Types

PHP is a loosely typed language. You don't have to tell the interpreter which type a certain variable is, you just have to assign a value to it, and PHP will know which type to treat it as. In the perfect world, you would never have to care about the type of a variable, but as we all know, the world is far from perfect. There will be many situations where controlling the type of a variable will make sense, and therefore, PHP does expose functions to detect and manipulate the type of a variable. First, a little bit of information about the various types in PHP

PHP supports the following data types:

  • String
  • Integer
  • Float
  • Boolean
  • Array
  • Object
  • Resource
  • NULL
  • PHP String

    A string is a sequence of characters, like "Hello world!". A string can be any text inside quotes. You can use single or double quotes:

    Example -

    PHP Integer

    a number with no decimals, e.g 3 or 42.

    PHP Float

    (sometimes referred to as double) - A number that may include decimals, e.g. 42.3 or 10.9.

    PHP Boolean

    A boolean is actually much like an integer, but with only two possible values: 0 or 1, which is either false or true.

    PHP Array

    holds an array of items, e.g. several strings or several integers. An array may contain variables which are arrays which are arrays and so on.

    PHP Object

    An object is a data type which stores data and information on how to process that data. In PHP, an object must be explicitly declared. First we must declare a class of object. For this, we use the class keyword. A class is a structure that can contain properties and methods:

    PHP Resource

    The special resource type is not an actual data type. It is the storing of a reference to functions and resources external to PHP. A common example of using the resource data type is a database call. We will not talk about the resource type here, since it is an advanced topic.

    NULL

    A value of null is nothing. It's not the same as 0 (zero), because that's actually a value. Null is truly nothing. Variables which have not yet been assigned a value, or which you have used the unset() method on, will carry the NULL value. This is useful if you wish to check whether or not a variable contains any value - you may compare it against the NULL constant. In the next couple of chapters, we will look into working with both strings and numbers (integers and floats), and later on, we will look into both arrays and objects.

    Working with numbers

    PHP have two different data types related to numbers: Integers and floats. Integers are whole numbers, without a decimal separator, while floats always carry a fractional part as well. In most cases, integers will be sufficient, and they are faster and simpler to work with. Let's try some simple calculations, to show you how easy it is to do math with PHP.

    Example -