PHP Data Types

In this lesson, you will learn about the different data types that the PHP Programming Language supports and examples to understand the topic better.


What are Data Types in PHP?

Before we talk about data types, let’s do a quick revision about Variables in PHP.

Variables are used in PHP programming to store information and track that information in a program. A few important things need to be mentioned regarding Data Types in PHP.

  • PHP uses a leading dollar sign $ to denote all the variables.
  • PHP uses the equal operator on the left and the variable’s value to be evaluated on the right.
  • PHP is a loosely typed language. Based on its context, a variable’s runtime determines its type. The programmer cannot assign it as PHP runtime does not distinguish the type of variable in advance.
  • When necessary, PHP automatically converts between different data types.
  • Instead of assigning default values to variables, PHP gives the most recent value.
  • PHP variables are like Perl.

PHP Data Types

PHP uses data types to create variables. The primary data types (boolean, integer, float, string) are simple, and the following two data types (arrays and objects) are compound. Compound data types can set other random values of any type, while simple data types cannot set the random type.


Below are The eight primitive data types that PHP supports:

Four scalar types

  1. boolean
  2. integer
  3. float
  4. string

Two compound types

  1. array
  2. object

Special types

  1. resource
  2. NULL

Tip
The double data type is the same as the float.

PHP Data Types checker Functions

PHP provides a few functions to check the type and value of an expression, such as var_dump() and is_type() functions. PHP supports the gettype() function for debugging purposes, especially for human-readable representation.

Example

<?php
$var_bool = true; // a boolean variable$var_str = "YESS"; // a string variable
$var_str2 = 'YES'; // a string variable
$var_int = 12; // an integer variable
echo "Type of variable = " . gettype($var_bool);
echo "<br>";
echo "Type and value of variable = ";
echo var_dump($var_bool);
echo "<br>";
echo "_____________________________________", "<br>";
echo "Type of variable = " . gettype($var_str);
echo "<br>";
echo "Type and value of variable = ";
echo var_dump($var_str);
echo "<br>";
// if condition is true, increment the integer by 10 otherwise not
echo "_____________________________________", "<br>";
if (is_int($var_int))
{
    $var_int = ($var_int - 10);
    echo "Is it int? $var_int" . "<br>";
}
// if condition is true, display result of string otherwise not
echo "_____________________________________", "<br>";
if (is_string($var_str2))
{
    echo "Is it String? $var_str2" . "<br>";
}
?>

Output

Type of variable = boolean
Type and value of variable = bool(true)
_____________________________________
Type of variable = string
Type and value of variable = string(4) "YESS"
_____________________________________
Is it int? 2
_____________________________________
Is it string? YES
Note
is_int() is used to determine the datatype of integers, is_bool() is used for Booleans, and is_string() is used to check the data type of string.

Different Data types in PHP explained

Integers

  • The non-decimal data type known as integers has a set of numbers that includes .........., -2, -1, 0, 1, 2,.......
  • The same rules apply to integers in all programming languages.
  • Integers contain at least one number without a decimal point.
  • A negative sign - is placed before negative integers.
  • The integers’ range is between -2147483648 and 2147483647.
  • Integers can also be in 10-based decimal, 16-based hexadecimal, or 8-based octal.

Example

<?php
// PHP var_dump() function display the value and data type.
$dec_var = 763;
echo '$dec_var = ';
var_dump($dec_var); // positive integer data type
echo "<br>";

$neg_var = - 763; // negative integer data type
echo '$neg_var = ';
var_dump($neg_var);
echo "<br>";

$hex_var = 0x5A; // 16-based hexadecimal
echo '$hex_var = ';
var_dump($hex_var);
echo "<br>";

$oc_var = 0323; // 8-based octal
echo '$oc_var = ';
var_dump($oc_var);
echo "<br>";

$var_sum = $oc_var + $hex_var; // Different based intergers can be added
echo 'Sum of $hex_var and $oc_var = ' . $var_sum;

?>

Output

$dec_var = int(763)
$neg_var = int(-763)
$hex_var = int(90)
$oc_var = int(211)
Sum of $hex_var and $oc_var = 301

Doubles

Floating-point numbers are the data type for doubles. They may contain fractional or decimal numbers with the + and sign. Double variables, by default, show the minimum number of decimal places necessary, such as 3.1414 or 26.12.

Example

<?php
$var_float = 19.9999998; // Fractional number
echo '$var_float = '; //double and float are same in PHP
var_dump($var_float);
echo "<br>";

$var_float2 = 23.981189999999;
$sum_float = $var_float + $var_float2;
echo '$var_float2 = ', $var_float2, "<br>";
echo '$var_float + $var_float2 = ', $sum_float, "<be>";
?>

Output

$var_float = float(19.9999998)
$var_float2 = 23.981189999999
$var_float + $var_float2 = 43.981189799999

Booleans

Because booleans can have either a true or false value, programmers frequently use them for conditional testing.

Example

<?php
$var_bool = true;
$var_bool2 = false;
var_dump($var_bool);
echo "<br>";
var_dump($var_bool2);
echo "<br>";
if ($var_bool2) echo ("Executed Boolean: TRUE<br>");
    else echo ("Executed Boolean: FALSE<be>");
?>

Output

bool(true)
bool(false)
Executed Boolean: FALSE

Booleans can be interpreted in other ways as well. A Boolean variable is any variable with a true or false value that is not of the Boolean type. For instance, in the first case involving integers, if the variable’s value is 1, it is considered valid, and if it equals 0, it is false. In the second scenario, a string is false if it contains no characters or is empty; otherwise, it is true. The third situation is the NULL type, which is always considered false. The fourth case involves arrays; if an array has any values, it is counted as valid; if it has null values, it is counted as false.

Example

<?php
$var_num_tbool = 1;
$var_str_tbool = "This is string true bool";
$true_array[49] = "An array element";
$var_array_fbool = array();
$var_null_bool = NULL;
$var_num_fbool = 999 - 999;
$var_str_fbool = "";

if ($var_num_tbool) // consider true bool
echo "True Integer Bool";
echo "<br>";
if (!$var_num_fbool) // will display as not false(true) is set
echo "False Integer Bool";
echo "<br>";
if ($var_str_tbool) // consider true bool
echo "True String Bool";
echo "<br>";
if (!$var_str_fbool) // will display as not false(true) is set
echo "False String Bool";
echo "<br>";
if (!$var_null_bool) // will display as not false(true) is set
echo "False NULL Bool";
echo "<br>";
if ($true_array) // consider true bool
echo "True Array Bool";
echo "<br>";
if (!$var_array_fbool) // will display as not false(true) is set
echo "False Array Bool";
echo "<br>";
?>

Output

True Integer Bool
False Integer Bool
True String Bool
False String Bool
False NULL Bool
True Array Bool
False Array Bool

NULL

As its name suggests, a NULL type can only contain one value. By convention, NULL is a capitalized constant, however, it’s not case-sensitive. Any variable with a NULL value is considered false in boolean calculations.

$var_null = NULL;

A crucial idea to comprehending NULL is that null is automatically assigned when a variable is created without a value set, such as $var_null. However, a double-quoted empty string is not regarded as null.

Let’s look at the assignments below.

$var_null1 = NULL and $var_null2 = "" are not considered equal. $var_null2 shows no value assigned to $var_null2 that is different than NULL.

Example

<?PHP
$var_null = NULL;
var_dump($var_null);
echo "<br>";
$var_null2 = "Make it NULL";
$var_null2 = NULL;
var_dump($var_null2);
echo "<br>";
$var_null3 = "";
var_dump($var_null3);
?>

Output

NULL
NULL
string(0) ""

Strings

A string data type is a collection of characters that can include letters, numbers, or any alphabet. Strings are enclosed in double or single quotes during declaration, but they have not been handled the same way during printing. No limits on string length are defined. Depending on your system memory, a group of characters may be saved as a long string of characters. Let’s look at an example below to help with this explanation.

Note
The strings Data Type will be discussed in detail later in this course.

Escape sequences

During string parsing, escape sequences are used to escape a character and display carriage-return characters, tabs, line breaks, etc. Escape sequences begin with the backslash \ followed by the alphanumeric or special character. Characters that start with \ give special meaning to that character, such as \n represents line breaks. Strings with character sequences are replaced with special characters, such as \n with the newline character, \r with the carriage-return character, \t with the tab character, \$ with the dollar sign itself $, \” with a single double-quote (“), \\ with single backslash (\).

Example

<?php
echo "Example Escape-Sequence";
echo "<br>";
echo "\r output carriage-return";
echo "<br>";
echo "\t output the tab";
echo "<br>";
echo " $ output dollar sign";
echo "<br>";
echo " \" single output double-quote ";
echo "<br>";
echo " \\ output single backslash";
echo "<be>";
?>

Output

Example Escape-Sequence
output carriage-return
output the tab
$ output dollar sign
" single output double-quote
\ output single backslash

Arrays

Arrays are named collections of values.

Example

<?php
$thesis_work = array(
    "Intro",
    "History",
    "Practical Implementation"
);
var_dump($thesis_work);
?>

Output

array(3) { [0]=> string(5) "Intro" [1]=> string(7) "History" [2]=> string(24) "Practical Implementation" }
Note
The Array Data Type will be discussed in detail later in this course.

Objects

Objects are instances of classes that can package up other kinds of values and functions specific to the class. The object data type also stores information on how to process that information. In PHP, objects are explicitly declared, and a class of objects is created.

Example

<?php
class Book
{
    function Book()
    {
        $this->Chapter = "Introduction to PHP";
    }
}
// create an object
$introduction = new Book();
echo $introduction->Chapter;
?>

Output

Introduction to PHP

Resources

Resource data type refers to an external resource such as opened files, database connections, etc.

Example

<?php
// Open a file for reading
$var_open_book = fopen("mybook.txt", "r");
var_dump($var_open_book);
echo "<be>";
?>

Output

resource(3) of type (stream)
// mybook.txt is placed in the same folder as this script.

This concludes the PHP Data Types lesson. In the next lesson, you will learn about comments in PHP.