PHP
In this tutorial we will learn about PHP data types.
PHP supports 8 data types. A variable's data type tells us about the type of operations that can be performed on the data and the memory space the value of that data type will occupy.
Following are the list of 4 simple data type. They can hold only one value at a time.
true
false
Following are the list of 2 compound data type. These are the data type that can hold multiple values.
We will talk about array and object in detail in their respective tutorial.
Following are the list of 2 special data type.
null
Now this is a very important point to note. PHP is loosely typed means that PHP does not care what value you store in a variable as the data type is automatically determined based on the context in which the variable is used.
For example
$x = 10;
In the above line we have created a variable $x and it is assigned an integer value 10. So, the data type of variable $x is Integer. Now we will do a very interesting thing.
$x = "Sunday";
We have now set a string value to the same variable $x. This time, the data type of variable $x is String.
The interesting thing is we can assign any type of value to a variable and the data type of that variable will be determined as per the current value it is holding.
This is completely different from strongly typed languages like Java and C++ where we cannot assign a string value to an integer variable as they are of different data type.
Note! The loosely typed nature of PHP can easily become a cause of error. So, take extra care while assigning value to variables.
We can use the function gettype() to determine the data type of a variable. Lets check few example.
gettype()
$name = "Yusuf Shakeel"; echo gettype($name);
This will print "string" as $name contains a String data.
$age; echo gettype($age);
This will print "null" as we have created a variable $age but it is not initialized with any value so it contains null.
We can also use the following functions to determine the data type of the variable.
We can change the data type of a variable using the settype() function. This function takes two parameters. The first one is for the variable and the second is for the type.
settype()
In the following example we are changing the data type of integer variable $x to string.
$x = 10; //this is an integer variable settype( $x, "string" ); //setting type of $x to string echo gettype($x); //this will print "string"
We can use type casting to change the variable's value to a specific type. In this method we are only targeting the value of the variable so the data type of the variable will remain unchanged.
$weight = 100.20; //data type float (double) echo gettype($weight); //double //now we will type cast the value of $weight to integer echo (int) $weight; //100 double value is changed to integer so fractional part is truncated. echo gettype( (int) $weight ); //integer this is the type of the value echo gettype($weight); //double