- 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
Flow control in PHP
In this part of the PHP tutorial, we talk about the flow control. We define several keywords that enable us to control the flow of the PHP script.
The if statement
The if
statement has the following general form:
if (expression) statement
The if
keyword is used to check if an expression is true. If it is true, a statement is then executed. The statement can be a single statement or a compound statement. A compound statement consists of multiple statements enclosed by curly brackets.
ifstatement.php
<?php $num = 31; if ($num > 0) echo "\$num variable is positive\n"; ?>
We have a $num
variable. It is assigned value 31. The if
keyword checks for a boolean expression. The expression is put between square brackets. The expression 31 > 0
is true, so the next statement is executed. Curly brackets are optional if there is only one statement to execute.
$ php ifstatement.php $num variable is positive
This is the output of the example.
ifstatement2.php
<?php $num = 31; if ($num > 0) { echo "\$num variable is positive\n"; echo "\$num variable equals to $num\n"; } ?>
If we intend to execute more than one statement, we have to put them inside square brackets. If we did not use them, only the first statement would be executed. Curly brackets form the body of the if
statement.
We can use the else
keyword to create a simple branch. If the expression inside the square brackets following the if keyword evaluates to false, the statement inside the else body is automatically executed.
boyorgirl.php
<?php $sex = "female"; if ($sex == "male") { echo "It is a boy\n"; } else { echo "It is a girl\n"; } ?>
We have a $sex
variable. It has "female" string. The boolean expression evaluates to false and we get "It is a girl" in the console.
$ php boyorgirl.php It is a girl
This is the output of the example.
We can create multiple branches using the elseif
keyword. The elseif
keyword tests for another condition if and only if the previous condition was not met. Note that we can use multiple elseif
keywords in our tests.
ifelsestm.php
<?php echo "Enter a number: "; $a = intval(fgets(STDIN)); if ($a < 0) { printf("%d is a negative number\n", $a); } elseif ($a == 0) { printf("%d is a zero\n", $a); } elseif ($a > 0) { printf("%d is a positive number\n", $a); } ?>
We read a value from the user using the fgets()
function. The value is tested if it is a negative number or positive or if it equals to zero.
$ php ifelsestm.php Enter a number: 4 4 is a positive number $ php ifelsestm.php Enter a number: -3 -3 is a negative number
Sample output of the program.
The switch statement
The switch
statement is a selection control flow statement. It allows the value of a variable or expression to control the flow of program execution via a multiway branch. It creates multiple branches in a simpler way than using the if
, elseif
statements.
The switch
statement works with two other keywords: case
and break
. The case
keyword is used to test a label against a value from the round brackets. If the label equals to the value, the statement following the case is executed. The break
keyword is used to jump out of the switch
statement. There is an optional default
statement. If none of the labels equals the value, the default statement is executed.
domains.php
<?php $domain = 'sk'; switch ($domain) { case 'us': echo "United States\n"; break; case 'de': echo "Germany\n"; break; case 'sk': echo "Slovakia\n"; break; case 'hu': echo "Hungary\n"; break; default: echo "Unknown\n"; break; } ?>
In our script, we have a $domains variable. It has the 'sk' string. We use the switch
statement to test for the value of the variable. There are several options. If the value equals to 'us' the 'United States' string is printed to the console.
$ php domains.php Slovakia
We get 'Slovakia'. If we changed the $domains variable to 'rr', we would get 'Unknown' string.
The while loop
The while
is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.
This is the general form of the while
loop:
while (expression): statement
The while
loop executes the statement when the expression is evaluated to true. The statement is a simple statement terminated by a semicolon or a compound statement enclosed in curly brackets.
whilestm.php
<?php $i = 0; while ($i < 5) { echo "PHP language\n"; $i++; } ?>
In the code example, we repeatedly print "PHP language" string to the console.
The while
loop has three parts: initialization, testing, and updating. Each execution of the statement is called a cycle.
$i = 0;
We initiate the $i
variable. It is used as a counter in our script.
while ($i < 5) { ... }
The expression inside the square brackets is the second phase, the testing. The while loop executes the statements in the body until the expression is evaluated to false.
$i++;
The last, third phase of the while
loop is the updating; a counter is incremented. Note that improper handling of the while
loop may lead to endless cycles.
$ php whilestm.php PHP language PHP language PHP language PHP language PHP language
The program prints a message five times to the console.
The do while
loop is a version of the while
loop. The difference is that this version is guaranteed to run at least once.
dowhile.php
<?php $count = 0; do { echo "$count\n"; } while ($count != 0) ?>
First the iteration is executed and then the truth expression is evaluated.
The while
loop is often used with the list()
and each()
functions.
seasons.php
<?php $seasons = ["Spring", "Summer", "Autumn", "Winter"]; while (list($idx , $val) = each($seasons)) { echo "$val\n"; } ?>
We have four seasons in a $seasons
array. We go through all the values and print them to the console. The each()
function returns the current key and value pair from an array and advances the array cursor. When the function reaches the end of the array, it returns false and the loop is terminated. The each()
function returns an array. There must be an array on the left side of the assignment too. We use the list()
function to create an array from two variables.
$ php seasons.php Spring Summer Autumn Winter
This is the output of the seasons.php
script.
The for keyword
The for
loop does the same thing as the while
loop. Only it puts all three phases, initialization, testing and updating into one place, between the round brackets. It is mainly used when the number of iteration is know before entering the loop.
Let's have an example with the for
loop.
forloop.php
<?php $days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]; $len = count($days); for ($i = 0; $i < $len; $i++) { echo $days[$i], "\n"; } ?>
We have an array of days of a week. We want to print all these days from this array.
$len = count($days);
Or we can programmatically figure out the number of items in an array.
for ($i = 0; $i < $len; $i++) { echo $days[$i], "\n"; }
Here we have the for
loop construct. The three phases are divided by semicolons. First, the $i
counter is initiated. The initiation part takes place only once. Next, the test is conducted. If the result of the test is true, the statement is executed. Finally, the counter is incremented. This is one cycle. The for
loop iterates until the test expression is false.
$ php forloop.php Monday Tuesday Wednesday Thursday Friday Saturday Sunday
This is the output of the forloop.php
script.
The foreach statement
The foreach
construct simplifies traversing over collections of data. It has no explicit counter. The foreach
statement goes through the array one by one and the current value is copied to a variable defined in the construct. In PHP, we can use it to traverse over an array.
foreachstm.php
<?php $planets = [ "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" ]; foreach ($planets as $item) { echo "$item "; } echo "\n"; ?>
In this example, we use the foreach
statement to go through an array of planets.
foreach ($planets as $item) { echo "$item "; }
The usage of the foreach
statement is straightforward. The $planets
is the array that we iterate through. The $item
is the temporary variable that has the current value from the array. The foreach
statement goes through all the planets and prints them to the console.
$ php foreachstm.php Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune
Running the above PHP script gives this output.
There is another syntax of the foreach
statement. It is used with maps.
foreachstm2.php
<?php $benelux = [ 'be' => 'Belgium', 'lu' => 'Luxembourgh', 'nl' => 'Netherlands' ]; foreach ($benelux as $key => $value) { echo "$key is $value\n"; } ?>
In our script, we have a $benelux
map. It contains domain names mapped to the benelux states. We traverse the array and print both keys and their values to the console.
$ php foreachstm2.php be is Belgium lu is Luxembourgh nl is Netherlands
This is the outcome of the script.
The break, continue statements
The break
statement is used to terminate the loop. The continue
statement is used to skip a part of the loop and continue with the next iteration of the loop.
testbreak.php
<?php while (true) { $val = rand(1, 30); echo $val, " "; if ($val == 22) break; } echo "\n"; ?>
We define an endless while
loop. There is only one way to jump out of a such loop—using the break
statement. We choose a random value from 1 to 30 and print it. If the value equals to 22, we finish the endless while loop.
$ php testbreak.php 6 11 13 5 5 21 9 1 21 22
We might get something like this.
In the following example, we print a list of numbers that cannot be divided by 2 without a remainder.
testcontinue.php
<?php $num = 0; while ($num < 1000) { $num++; if (($num % 2) == 0) continue; echo "$num "; } echo "\n"; ?>
We iterate through numbers 1..999 with the while
loop.
if (($num % 2) == 0) continue;
If the expression $num % 2
returns 0, the number in question can be divided by 2. The continue
statement is executed and the rest of the cycle is skipped. In our case, the last statement of the loop is skipped and the number is not printed to the console. The next iteration is started.
In this part of the PHP tutorial, we were talking about control flow structures.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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