- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
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
- boolean
- integer
- float
- string
Compound types
- array
- object
Special types
- resources
- NULL
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:
- it was not assigned a value
- it was assigned a special NULL constant
- it was unset with the unset() function
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论