A Datatype defines the type of data. In PHP we do not need to strictly define data type for data.
PHP data types are divided into two broad categories.
- Scalar Data Type: for example integer, float, string and boolean
- Compound Data Type: they are container of other data types. examples of compound data types are arrays, resources and objects
PLEASE NOTE: There is a particular datatype that only means a variable has no value: NULL. Null is a case insensitive keyword, so you can write it as null, NULL, Null and so on..
Type Casting in PHP
PHP automatically converts data types. In addition, this type casting can also be enforced using type conversion operators. Type conversion operators are simply the name of data type enclosed in parenthesis and placed before the expression.
$var = (data type) expression;
1 2 3 4 5 6 7 8 |
<?php #datatypes.php //typecasting as integer $mytype = (int) 54.99; echo "<p>The converted value is: $mytype</p>"; /* the converted value is: 54 */ ?> |
You can use gettype() function to retrieve the data type of a variable:
1 2 3 4 5 6 7 |
<?php #datatypes.php $value = 123; echo "<p>Your value datatype is: <strong>" . gettype( $value ) . "</strong>.</p>"; /* Your value datatype is: integer. */ ?> |
PLEASE NOTE: If you use gettype() to get the datatype of a float variable (e.g. 1.5) you will get double. Double is just the old name of the float datatype.
If you want to test variables against a certain datatype you can use one of the following functions:
- is_string()
- is_float()
- is_int()
- is_bool()
- is_array()
- is_object()
- is_resource()
- is_null()
All those functions will return a boolean value (true/false)
Click here to read about PHP operators.