In this part of the PHP tutorial, we will talk about data types.
Computer programs work with data. Spreadsheets, text editors, calculators or chat clients. Tools to work with various data types are essential part of a modern computer language. According to the wikipedia definition, a
PHP has eight data types:
Scalar types
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.
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.
In 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 three different notations in PHP. Decimal, hexadecimal and octal. Octal values are preceded by 0, hexadecimal by 0x.
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.
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.
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. We would use integers to count apples.
We can use various syntax to create floating point values.
According to the documentation, floating point numbers should not be tested for equality. We will show an example why.
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
Since string are very important in every programming language, we will dedicate a whole chapter to them. Here we only drop a small example.
Because collections are very important in all computer languages, we dedicate two chapters to collections - arrays. Here we show only a small example.
In PHP, a variable is NULL in three cases:
Explicit conversion happens, when we use the cast constructs, like (boolean).
In this part of the PHP tutorial, we covered data types.
Computer programs work with data. Spreadsheets, text editors, calculators or chat clients. Tools to work with various data types are essential part of a modern computer language. According to the wikipedia definition, a
data type
is a set of values, and the allowable operations on those values.PHP has eight data types:
Scalar types
- boolean
- integer
- float
- string
- array
- object
- resources
- NULL
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. Very common in computer programs.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.
<?phpThe script uses a random integer generator to simulate our case.
$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";
}
?>
$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) {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.
echo "We will use name John\n";
} else {
echo "We will use name Victoria\n";
}
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.
<?phpIn this script, we inspect some values in a boolean context. The
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);
?>
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.phpHere is the outcome of the script.
bool(false)
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
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 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 three different notations in PHP. Decimal, hexadecimal and octal. Octal values are preceded by 0, hexadecimal by 0x.
<?phpWe assign 31 to three variables using three notations. And we print them to the console.
$var1 = 31;
$var2 = 031;
$var3 = 0x31;
echo "$var1\n";
echo "$var2\n";
echo "$var3\n";
?>
$ php notation.phpThe default notation is the decimal. The script shows these three numbers in decimal.
31
25
49
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 -moOn my 32bit Ubuntu system, an integer value size is four bytes. The maximum integer value is 2147483647.
i686 GNU/Linux
$ php -a
Interactive shell
php > echo PHP_INT_SIZE;
4
php > echo PHP_INT_MAX;
2147483647
php >
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.
<?phpWe assign a maximum integer value to the $var variable. We increase the variable by one. And we compare the contents.
$var = PHP_INT_MAX;
echo var_dump($var);
$var++;
echo var_dump($var);
?>
$ php boundary.phpAs we have mentioned previously, internally, the number becomes a floating point value.
int(2147483647)
float(2147483648)
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. We would use integers to count apples.
<?phpIn our script, we count the total amount of apples. We use the multiplication operation.
# 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";
?>
$ php apples.phpThe output of the script.
There are total of 384 apples
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.
<?phpIn 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.
$a = 1.245;
$b = 1.2e3;
$c = 2E-10;
$d = 1264275425335735;
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>
$ php floats.phpThis is the output of the above script.
float(1.245)
float(1200)
float(2.0E-10)
float(1264275425340000)
According to the documentation, floating point numbers should not be tested for equality. We will show an example why.
$ php -aIn this example, we compare two values that seem to be identical. But they yield unexpected result.
Interactive shell
php > echo 1/3;
0.333333333333
php > $var = (0.333333333333 == 1/3);
php > var_dump($var);
bool(false)
php >
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
<?phpIn this example, it is necessary to use floating point values.
# 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";
?>
$speed = $distance / $time;To get the speed, we divide the distance by the time.
$ php sprinter.phpThis is the output of the sprinter script. 36.4741641337 is a floating point number.
The average speed of a sprinter is 36.4741641337
Strings
String
is a data type representing textual data in computer programs. Probably the single most important data type in programming. Since string are very important in every programming language, we will dedicate a whole chapter to them. Here we only drop a small example.
<?phpWe can use single quotes and double quotes to create string literals.
$a = "PHP ";
$b = 'PERL';
echo $a, $b;
echo "\n";
?>
$ php strings.phpThe 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.
PHP PERL
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 diverse. 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.
<?phpThe
$names = array("Jane", "Lucy", "Timea", "Beky", "Lenka");
print_r($names);
?>
array
keyword is used to create a collection of elements. In our case we have names. The print_r
function prints a human readable information about a variable to the console. $ php init.phpOutput of the script. The numbers are indeces by which we can access the names.
Array
(
[0] => Jane
[1] => Lucy
[2] => Timea
[3] => Beky
[4] => Lenka
)
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:
- it was not assigned a value
- it was assigned a special NULL constant
- it was unset with the unset() function
<?phpIn our example, we have four variables. Three of them are considered to be NULL. We use the
$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";
?>
is_null()
function to determine, if the variable is NULL. $ php null.phpOutcome of the script.
$a is null
$b is null
$c is null
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;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.
57
php > echo 12 + 12.4;
24.4
Explicit conversion happens, when we use the cast constructs, like (boolean).
php > $a = 12.43;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 boolean data type.
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)
In this part of the PHP tutorial, we covered data types.
0 comments:
Post a Comment