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 typeExampleDescription
String“Hello”Text, in single or double quotes
Integer100, -5Whole numbers without a decimal point
Float (double)10.5, 3.14Numbers with a decimal point
Booleantrue, falseOnly two values, used in conditions
Array[1, 2, 3]Many values in one variable. See PHP Arrays
Objectnew Car()An instance of a class. See PHP Objects
NULLnullA variable with no value. See What is NULL?
Resourcefile handleA 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:

Tutorials Class - Output Window

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:

Tutorials Class - Output Window

int(123)
float(3.14)
string(2) “45”
bool(false)
array(1) {
[0]=>
string(3) “PHP”
}

Note: PHP also changes types by itself when needed, for example "10" + 5 gives 15. This is called type juggling, and it can create bugs. Read type juggling and strict_types.

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.2 is not exactly 0.3.
  • Empty values like 0, “” and false all behave as false in a condition. See PHP empty().

Next chapter: PHP Constants.


Congratulations! Chapter Finished. Learn more about the similar topics:
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
Interview Questions & Answers
How to check if a variable is empty in PHP?
Is PHP a case sensitive language?
What are the different data types in PHP?
How to define a Constant in PHP?
What is the difference between $var and $$var in PHP?
Which special characters are allowed in PHP variable names?
Can we print multiple variables in a single echo statement in PHP?