PHP Data types – All data stored in PHP variables fall into one of eight basic categories, known as data types. A variable’s data type determines what operations can be carried out on the variable’s data, as well as the amount of memory needed to hold the data.
PHP supports four scalar data types. Scalar data means data that contains only a single value. Here is a list of them, including examples:
|Scalar data types||Description||Example|
|Integer||A whole number||15|
|float||A Floating-point number||9.03|
|String||A series of characters||“My name”|
|Boolean||Represents either true or false||false|
As well as the four scalar types, PHP supports two compound types . Compound data is data that can contain more than one value. The following table describes PHP’s compound types:
|Compound data type||Description|
|Array||An ordered map(contains name or numbers mapped to values)|
|Object||A type that may contains properties and method|
Finally, PHP supports two special data types, so called because they don’t contain scalar or compound data as such, but have a specific meaning:
|Special data Types||Description|
|Resource||Contains a reference to an external resources, such as a file or database|
|Null||May only contains null as a value, meaning the variable explicitly does not contain any value|
PHP loose Typing
PHP is known as a loosely-typed language. This means that it is not particularly fussy about the type of data stored in a variable. It converts a variable’s data type automatically, depending on the on the context in which the variable is used. For example, you can initialize a variable with an integer value; add a float value to it , thereby turning it into a float; then join it into a string value to produce a longer string. In contract, many other languages, such as java, are stongly-typed; once you set the type of a variable in java, it must always contain data of that type.
PHP’s loose typing is both good and bad. On the plus side, this makes variable very flexible; the same variable can easily be used in different situations. It also means that you don’t need to worry about specifying the type of a variable when you declare it. However, PHP won’t tell you if you accidentally pass around data of the wrong type. For example, PHP will happily let you pass a Floating-point value to a piece of code that expects to be a working on an integer value. You probably won’t see an error message, but you may discover that the output of your script is not quite what you expected! These types of errors can be hard to track down.(Fortunately, there is a way to test the type of a variable, as you see in a moment).