PHP Data Types
A data type tells what kind of value a variable holds, for example a number or a text. PHP is a loosely typed language, so you do not write the type yourself. PHP decides it from the value, and it can change when you assign a new value.
Types of data in PHP
| Data type | Example | Description |
|---|---|---|
| String | “Hello” | Text, in single or double quotes |
| Integer | 100, -5 | Whole numbers without a decimal point |
| Float (double) | 10.5, 3.14 | Numbers with a decimal point |
| Boolean | true, false | Only two values, used in conditions |
| Array | [1, 2, 3] | Many values in one variable. See PHP Arrays |
| Object | new Car() | An instance of a class. See PHP Objects |
| NULL | null | A variable with no value. See What is NULL? |
| Resource | file handle | A reference to an outside resource, like an open file |
Check the data type
Use var_dump() to see the type and the value, and gettype() to get only the type name.
<?php
$a = "Hello";
$b = 100;
$c = 10.5;
$d = true;
$e = [1, 2, 3];
$f = null;
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
var_dump($f);
?>
Output:
string(5) “Hello”
int(100)
float(10.5)
bool(true)
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
NULL
More ways are shown in how to check the data type of a variable.
Type casting
You can change a value from one type to another by writing the new type in brackets before the value. This is called type casting.
<?php
var_dump((int) "123abc");
var_dump((float) "3.14");
var_dump((string) 45);
var_dump((bool) "0");
var_dump((array) "PHP");
?>
Output:
int(123)
float(3.14)
string(2) “45”
bool(false)
array(1) {
[0]=>
string(3) “PHP”
}
Quick facts
- A string can use single quotes (text as it is) or double quotes (variables inside are replaced).
- The largest integer on a 64-bit system is
PHP_INT_MAX. A bigger number becomes a float. - Float numbers are not always exact, for example
0.1 + 0.2is not exactly 0.3. - Empty values like 0, “” and false all behave as false in a condition. See PHP empty().
Next chapter: PHP Constants.
| Exercises & Assignments |
|---|
| Write a program to print “Hello PHP” using variable |
| Write a program to print a string using echo+variable. |
| Write a program to print two variables in single echo |