As we already know about the Variable Scopes, let’s check out the supported data types in PHP. There are a total of 8 datatypes in PHP, which helps us identify the type of data a particular variable holds.
There happens an implicit conversion of datatypes in PHP, which means that we don’t specify the datatype while declaring a PHP variable. Based on the value that gets assigned to a variable, PHP engine implicitly determines the datatype and assigns it to that variable. To understand this better, let’s check out the PHP code below:
$b = 10;
var_dump($a); // prints int(10)
var_dump($b); // prints NULL
$a = 10.50;
var_dump($a); // prints float(10.5)
$b = 11.50;
var_dump($b); // prints float(11.5)
- Variable a has just been declared without initialization. Though it’s not recommended, variable a in this case holds a NULL value. We can also say that, variable a is still unaware of what type of data it is going to hold.
- Variable b has been declared and initialized with a value of 10. So, as expected, var_dump-ing it, prints 10 with an implicit cast of variable b to int.
- Variable a now gets initialized with a value of 10.50. So, as expected, var_dump-ing it, prints 10.5 with an implicit cast of variable a from type NULL to int.
- Variable b now gets assigned a value of 11.50. So, as expected, var_dump-ing it, prints 11.5 with an implicit cast of variable b from type int to float.
The datatypes supported by PHP are:
- String – anything within double quotes can be called as a String. Eg: $a = “Yash”;
- Integer – any number. Eg: $b = 5;
- Float – any number with a decimal point. Eg: $c = 1.5;
- Boolean – true/false Eg: $d = true;
- Array – collection of similar datatypes. Eg: $e = array(1,2,3,4,5);
- Object – will be learn about this in Object Oriented PHP
- NULL– a variable without having any value Eg: $f = null;
- Resource – not actually a datatype. It stores the reference to functions and resources external to PHP, which we will be exploring more when we connect our PHP application with MySQL.