PHP data types

In this part of the PHP tutorial, we will talk about data types.

Computer programs work with data. Tools to work with various data types are essential part of a modern computer language. A data type is a set of values and the allowable operations on those values.

PHP has eight data types:

Scalar types

Compound types

Special types

Unlike in languages like Java, C, or Visual Basic, in PHP we do not provide an explicit type definition for a variable. A variable's type is determined at runtime by PHP. If we assign a string to a variable, it becomes a string variable. Later if we assign an integer value, the variable becomes an integer variable.

Boolean values

There is a duality built in our world. There is a Heaven and Earth, water and fire, jing and jang, man and woman, love and hatred. In PHP the boolean data type is a primitive data type having one of two values: True or False. This is a fundamental data type.

Happy parents are waiting a child to be born. They have chosen a name for both possibilities. If it is going to be a boy, they have chosen John. If it is going to be a girl, they have chosen Victoria.

kid.php
<?php

$male = False;

$r = rand(0, 1);

$male = $r ? True: False;

if ($male) {
    echo "We will use name John\n";
} else {
    echo "We will use name Victoria\n";
}
?>

The script uses a random integer generator to simulate our case.

$r = rand(0, 1);

The rand() function returns a random number from the given integer boundaries. In our case 0 or 1.

$male = $r ? True: False;

We use the ternary operator to set a $male variable. The variable is based on the random $r value. If $r equals to 1, the $male variable is set to True. If $r equals to 0, the $male variable is set to False.

if ($male) {
    echo "We will use name John\n";
} else {
    echo "We will use name Victoria\n";
}

We print the name. The if command works with boolean values. If the variable $male is True, we print the "We will use name John" to the console. If it has a False value, we print the other string.

$ php kid.php 
We will use name Victoria
$ php kid.php 
We will use name John
$ php kid.php 
We will use name Victoria
$ php kid.php 
We will use name Victoria

The script is run a few times.

The following script shows some common values that are considered to be True or False. For example, empty string, empty array, 0 are considered to be False.

boolean.php
<?php
class Object {};

var_dump((bool) "");
var_dump((bool) 0);
var_dump((bool) -1);
var_dump((bool) "PHP");
var_dump((bool) array(32));
var_dump((bool) array());
var_dump((bool) "false");
var_dump((bool) new Object());
var_dump((bool) NULL);
?>

In this script, we inspect some values in a boolean context. The var_dump() function shows information about a variable. The (bool) construct is called casting. In its casual context, the 0 value is a number. In a boolean context, it is False. The boolean context is when we use (bool) casting, when we use certain operators (negation, comparison operators) and when we use if/else, while keywords.

$ php boolean.php
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)

Here is the outcome of the script.

Integers

Integers are a subset of the real numbers. They are written without a fraction or a decimal component. Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...}. Integers are infinite.

In many computer languages, integers are primitive data types. Computers can practically work only with a subset of integer values, because computers have finite capacity. Integers are used to count discrete entities. We can have 3, 4, 6 humans, but we cannot have 3.33 humans. We can have 3.33 kilograms.

Integers can be specified in four different notations in PHP: decimal, hexadecimal, octal, and binary. Octal values are preceded by 0, hexadecimal by 0x, and binary by 0b.

notation.php
<?php

$decimal_var = 31;
$octal_var = 031;
$hexadecimal_var = 0x31;
$binary_var = 0b01001110;

echo "$decimal_var\n";
echo "$octal_var\n";
echo "$hexadecimal_var\n";
echo "$binary_var\n";

?>

We define four variables; each of them has a different integer notation.

$ php notation.php 
31
25
49
78

The default notation is the decimal. The script prints these four numbers in decimal.

Integers in PHP have a fixed maximum size. The size of integers is platform dependent. PHP has built-in constants to show the maximum size of an integer.

$ uname -mo
x86_64 GNU/Linux
$ php -a
Interactive mode enabled

php > echo PHP_INT_SIZE;
8
php > echo PHP_INT_MAX;
9223372036854775807

On my 64 bit Ubuntu Linux system, an integer value size is eight bytes. The maximum integer value is 9223372036854775807.

In Java and C, if an integer value is bigger than the maximum value allowed, integer overflow happens. PHP works differently. In PHP, the integer becomes a float number. Floating point numbers have greater boundaries.

boundary.php
<?php

$var = PHP_INT_MAX;

echo var_dump($var);
$var++;
echo var_dump($var);

?>

We assign a maximum integer value to the $var variable. We increase the variable by one. The var_dump() function dumps information about a given variable.

$ php boundary.php 
int(9223372036854775807)
float(9.2233720368548E+18)

As we have mentioned previously, internally, the number becomes a floating point value.

In Java, the value after increasing would be -2147483648. This is where the term integer overflow comes from. The number goes over the top and becomes the smallest negative integer value assignable to a variable.

If we work with integers, we deal with discrete entities. For instance, we would use integers to count apples.

apples.php
<?php

# number of baskets
$baskets = 16;

# number of apples in each basket 
$apples_in_basket = 24;

# total number of apples
$total = $baskets * $apples_in_basket;

echo "There are total of $total apples \n";
?>

In our script, we count the total amount of apples. We use the multiplication operation.

$ php apples.php 
There are total of 384 apples 

The output of the script.

Floating point numbers

Floating point numbers represent real numbers in computing. Real numbers measure continuous quantities, like weight, height, or speed. Floating point numbers in PHP can be larger than integers and they can have a decimal point. The size of a float is platform dependent.

We can use various syntax to create floating point values.

floats.php
<?php

$a = 1.245;
$b = 1.2e3;
$c = 2E-10;
$d = 1264275425335735;

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);

?>

In this example, we have two cases of notations that are used by scientists to denote floating point values. Also the $d variable is assigned a large number, so it is automatically converted to float type.

$ php floats.php 
float(1.245)
float(1200)
float(2.0E-10)
int(1264275425335735)

This is a sample output of the above script.

According to the documentation, floating point numbers should not be tested for equality. We will show an example why.

$ php -a
Interactive mode enabled

php > echo 1/3;
0.33333333333333
php > $var = (0.33333333333333 == 1/3);
php > var_dump($var);
bool(false)

In this example, we compare two values that seem to be identical, but they yield unexpected result.

Let's say a sprinter for 100 m ran 9.87 s. What is his speed in km/h?

sprinter.php
<?php

# 100m is 0.1 km

$distance = 0.1;

# 9.87s is 9.87/60*60 h

$time = 9.87 / 3600;

$speed = $distance / $time;

echo "The average speed of a sprinter is $speed \n";

?>

In this example, it is necessary to use floating point values.

$speed = $distance / $time;

To get the speed, we divide the distance by the time.

$ php sprinter.php 
The average speed of a sprinter is 36.474164133739 

This is the output of the sprinter script. 36.474164133739 is a floating point number.

It is often necessary to round floating point numbers.

rounding.php
<?php

$a = 1.4567;

echo round($a, 2) . "\n";
echo round($a, 3) . "\n";

echo sprintf("%0.3f", $a) . "\n" ;

?>

In this example, it is necessary to use floating point values.

echo round($a, 2) . "\n";
echo round($a, 3) . "\n";

Using the round() function, we round the floting point value to two and three places.

echo sprintf("%0.3f", $a) . "\n" ;

Alternatively, we can also use the sprintf() function which formats a string according to the specified formatting string.

$ php rounding.php 
1.46
1.457
1.457

This is the output of the rounding.php script.

Strings

A string is a data type representing textual data in computer programs.

Since strings are very important in every programming language, we will dedicate a whole chapter to them. Here we only drop a small example.

strings.php
<?php

$a = "PHP ";
$b = 'Perl';

echo $a, $b;
echo "\n";

?>

We can use single quotes and double quotes to create string literals.

$ php strings.php 
PHP Perl

The script outputs two strings to the console. The \n is a special sequence, a new line. The effect of this character is like if you hit the enter key when typing text.

Arrays

Array is a complex data type which handles a collection of elements. Each of the elements can be accessed by an index. In PHP, arrays are more complex. Arrays can be treated as arrays, lists, or dictionaries. In other words, arrays are all what in other languages we call arrays, lists, dictionaries.

Because collections are very important in all computer languages, we dedicate two chapters to collections - arrays. Here we show only a small example.

arrays.php
<?php

$names = [ "Jane", "Lucy", "Timea", "Beky", "Lenka" ];

print_r($names);

?>

An array is created with the shorthand notation, where we use the square brackets. The elements of an array are separated with a comma character. The elements are strings. The print_r() function prints a human readable information about a variable to the console.

$ php arrays.php 
Array
(
    [0] => Jane
    [1] => Lucy
    [2] => Timea
    [3] => Beky
    [4] => Lenka
)

This is the output of the script. The numbers are indeces by which we can access the array elements.

Objects

So far, we have been talking about built-in data types. Objects are user defined data types. Programmers can create their data types that fit their domain. More about objects in chapter about object oriented programming, OOP.

Resources

Resources are special data types. They hold a reference to an external resource. They are created by special functions. Resources are handlers to opened files, database connections, or image canvas areas.

NULL

There is another special data type - NULL. Basically, the data type means non existent, not known or empty.

In PHP, a variable is NULL in three cases:

nulltype.php
<?php

$a;
$b = NULL;

$c = 1;
unset($c);

$d = 2;

if (is_null($a)) echo "\$a is null\n";
if (is_null($b)) echo "\$b is null\n";
if (is_null($c)) echo "\$c is null\n";
if (is_null($d)) echo "\$d is null\n";

?>

In our example, we have four variables. Three of them are considered to be NULL. We use the is_null() function to determine if the variable is NULL.

$ php nulltype.php 
$a is null
$b is null
$c is null

This is the outcome of the script.

Type casting

We often work with multiple data types at once. Converting one data type to another one is a common job in programming. Type conversion or typecasting refers to changing an entity of one data type into another. There are two types of conversion: implicit and explicit. Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler.

php > echo "45" + 12;
57
php > echo 12 + 12.4;
24.4

In the above example, we have two examples of implicit type casting. In the first statement, the string is converted to integer and added to the second operand. If either operand is a float, then both operands are evaluated as floats, and the result will be a float.

Explicit conversion happens when we use the cast constructs, like (boolean).

php > $a = 12.43;
php > var_dump($a);
float(12.43)
php > $a = (integer) $a;
php > var_dump($a);
int(12)
php > $a = (string) $a;
php > var_dump($a);
string(2) "12"
php > $a = (boolean) $a;
php > var_dump($a);
bool(true)

This code snippet shows explicit casting in action. First we assign a float value to a variable. Later we cast it to integer, string, and finally to a boolean data type.

In this part of the PHP tutorial, we covered PHP data types.