Data Types in PHP | PHP Data Types
Data Type in any programming language used to specify type of data which may be Boolean, Integer, Float, Double, String Character, etc. In PHP there are mainly four types of data type :
- Boolean
- Float
- Integer
- String
Besides these four we will see Array, Object, Resources and Null as data type in PHP.
1. Boolean data type in PHP :
This data type can have only one of the two values either True (1) or False (0) and can be used with condition.
Any value (false or FALSE , 0, 0.0 , empty string, ‘0’ , NULL will be considered as FALSE)
Example :
<?php $bvar=TRUE; echo $bvar; var_dump($bvar); //will return data type and value of the variable echo gettype($bvar); ?>
Output :
Note : var_dump() function returns data type & value of that variable.
2. Float data type in PHP :
Float or double data type is used for decimal number or floating point numbers.
For example 3.14, 2.5678
Example :
<?php $fvar=3.1345; echo $fvar . "</br>"; echo gettype($fvar). "</br>"; $fvar=34e5; echo $fvar; ?>
Output :
3. Integer data type in PHP :
This data type is used with the numbers that are without decimal and can be negative or positive.
With this data type you can also specify octal and hexadecimal numbers. Ex: 0, 2, 342 , -678 , 0x7C , 167 etc.
Example :
<?php $ivar=334; echo $ivar . "</br>"; echo gettype($ivar). "</br>"; $ivar=-678; echo $ivar; ?>
Output :
4. String data type in PHP :
“Sequence of characters” is called string delimited by single or double quotes.
Example :
<?php $svar="Hello.."; echo $svar. "</br>"; echo gettype($svar). "</br>"; $str='how are you ?'; echo $str. "</br>"; echo $svar . $str; ?>
Output :
Lets see compound types in PHP i.e. Array and objects and two other data types Null and resources.
5. Array data type in PHP:
An array is a kind of special variable having more than one value which shares same name but different index or id. Array can be used to store single or multiple data type.
Read more on Array In PHP : Array in PHP
Example :
<?php $Astr = array('DELHI' , 'MUMBAI', 'BANGLORE'); echo gettype($Astr). "</br>"; foreach( $Astr as $Val) { echo "</br>", $Val; } ?>
Output :
6. Objects in PHP :
Objects are the instance of the class with some properties and values.
7. Null in PHP : NULL mean not known, not existent or empty or no value of variable. It is used to differentiate null value and empty string.
You can assign null values by this way: Using NULL constant, by assigning No value and by using unset() function.
Example :
<?php $Y=NULL; echo $Y; $Z=10; if(is_null($Z)) echo "Z is Null"; else echo "Z is not Null"; ?>
Output :
8. Resources in PHP :
This data type holds the reference or links of the external resources. This link or reference may be of file connection, database connection, shared library, etc.