PHP Data Types - Introduction & Examples


Tutorial Topic:

PHP Data types are the types of data PHP Variables can store. PHP supports the following data types:

1. PHP String

String is basically a piece of text or a sequence of characters, like "Hello world!". Strings need to be wrapped in either " " or ' '. Any HTML tag or code snippet is also considered a string in PHP. For example:

$hi = 'Hello World!';
$hello = "How are you?";

echo $hi;
echo '<br/>';
echo $hello;

The output will be:

Hello World!
How are you?

2. PHP Integer

Any non-decimal number between -2,147,483,648 and 2,147,483,647 is considered an Integer in PHP.  An integer must have at least one digit, which can be either positive or negative. Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), and binary (base 2) notations. Integers are used without " " or ' ' in PHP statements. Like:

$x = 1234;
echo $x;

The above example stores the integer 1234 in a PHP variable $x and then shows it on the screen.

3. PHP Float


A floating point number (PHP float) is a number either in a decimal form or an exponential form. Float is also called a double. Floats are used without " " or ' ' in PHP statements. Like:

$x = 12.34;
echo $x;

The above example stores the decimal number (float) 12.34 in a PHP variable $x and then shows it on the screen.

4. PHP Boolean

A Boolean data type represents wither of the two possible states:

  • 1 or 0

Boolians are mostly used in conditional testing and without " " or ' ' in PHP statements. , like:

$x = true;
$y = false;


5. PHP Array

Arrays are used to store multiple values in one single variable. In the example below, $names is an array and it is storing 3 values (names) in it. Arrays are mostly used for grouped data like a set of data in a person's profile or a collection of fruits.

$names = array("Sami","David","Ali");
print_r ($names);


6. PHP Object

A PHP object is a type of data, which stores the data and information on how to process that data. To use PHP objects first we must declare a class of object using the class keyword. A class is a structure that can contain properties and methods: In PHP, an object must be explicitly declared.

 For example:

class Fruit {
    function Fruit() {
        $this->color = "Yellow";
// create an object
$mango = new Fruit();
// show object properties
echo $mango->color;

The above example will output Yellow.