In this part of the PHP tutorial, we will talk about the flow control. We will define several keywords that enable us to control the flow of the PHP script.
We can use the
The
This is the general form of the
The
There is another version of the
The
Let's have an example with the
There is another syntax of the
In the following example, we will print a list of numbers, that cannot be divided by 2 without a remainder.
In this part of the PHP tutorial, we were talking about control flow structures.
The if statement
Theif
statement has the following general form: if (expression)The
statement
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 of a compound statement. A compound statement consists of multiple statements enclosed by curly brackets. <?phpWe have a $num variable. It is assigned 31. The
$num = 31;
if ($num > 0)
echo "\$num variable is positive\n";
?>
if
keyword checks for a boolean expression. The expression is put between square brackets. 31 > 0 is true, so the next statement is executed. $ php positive.php
$num variable is positive
<?phpIf 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.
$num = 31;
if ($num > 0) {
echo "\$num variable is positive\n";
echo "\$num variable equals to $num\n";
}
?>
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. <?phpWe have a $sex variable. It has "female" string. The boolean expression evaluates to false and we get "It is a girl" in the console.
$sex = "female";
if ($sex == "male") {
echo "It is a boy\n";
} else {
echo "It is a girl\n";
}
?>
$ php boyorgirl.phpWe can create multiple branches using the
It is a girl
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. <?phpWe have a numerical variable and we test it, if it is a negative number or positive or if it equals to zero. The first expression evaluates to false. The second condition is met. The script prints '$a is zero' to the console. The rest of the branch is skipped.
$a = 0;
if ($a < 0) {
echo "\$a is a negative number\n";
} elseif ($a == 0) {
echo "\$a is zero\n";
} else {
echo "\$a is a positive number\n";
}
?>
The switch statement
Theswitch
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. The case
and the break
statements. 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. <?phpIn our script, we have a $domains variable. It has the 'sk' string. We use the
$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;
}
?>
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.phpWe get 'Slovakia'. If we changed the $domains variable to 'rr', we would get 'Unknown' string.
Slovakia
The while loop
Thewhile
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):The
statement
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. <?phpIn the code example, we print "PHP language" string five times to the console.
$i = 0;
while ($i < 5) {
echo "PHP language\n";
$i++;
}
?>
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. The updating. We increment the counter. Note, that improper handling of the while
loops may lead to endless cycles. There is another version of the
while
loop. It is the do while
loop. The difference between the two is that this version is guaranteed to run at least once. <?phpFirst the iteration is executed and then the truth expression is evaluated.
$count = 0;
do {
echo "$count\n";
} while ($count != 0)
?>
The
while
loop is often used with the list()
and each()
functions. <?phpWe have four seasons in a $seasons array. We go through all the values and print them to the console. The
$seasons = array("Spring", "Summer", "Autumn", "Winter");
while (list($idx , $val) = each($seasons)) {
echo "$val\n";
}
?>
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. The for keyword
Thefor
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. <?phpWe have an array of days of a week. We want to print all these days from this array. We all know that there are seven days in a week.
$days = array("Monday", "Tuesday", "Wednesday",
"Thursday", "Friday",
"Saturday", "Sunday");
$len = count($days);
for ($i = 0; $i < $len; $i++) {
echo $days[$i], "\n";
}
?>
$len = count($days);Or we can programatically figure out the number of items in an array.
for ($i = 0; $i < $len; $i++) {Here we have the
echo $days[$i], "\n";
}
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. The foreach statement
Theforeach
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. <?phpIn this example, we use the
$planets = array("Mercury", "Venus", "Earth", "Mars", "Jupiter",
"Saturn", "Uranus", "Neptune");
foreach ($planets as $item) {
echo "$item ";
}
echo "\n";
?>
foreach
statement to go through an array of planets. foreach ($planets as $item) {The usage of the
echo "$item ";
}
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 planets.phpRunning the above PHP script gives this output.
Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune
There is another syntax of the
foreach
statement. It is used with maps. <?phpIn 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.
$benelux = array(
'be' => 'Belgium',
'lu' => 'Luxembourg',
'nl' => 'Netherlands'
);
foreach ($benelux as $key => $value) {
echo "$key is $value\n";
}
?>
$ php benelux.phpThis is the outcome of the script.
be is Belgium
lu is Luxembourg
nl is Netherlands
The break, continue statements
Thebreak
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. <?phpWe define an endless
while (true) {
$val = rand(1, 30);
echo $val, " ";
if ($val == 22) break;
}
echo "\n";
?>
while
loop. There is only one way to jump out of a such loop. We must use the break
statement. We choose a random value from 1 to 30. We print the value. If the value equals to 22, we finish the endless while loop. $ php testbreak.phpWe might get something like this.
6 11 13 5 5 21 9 1 21 22
In the following example, we will print a list of numbers, that cannot be divided by 2 without a remainder.
<?phpWe iterate through numbers 1..999 with the
$num = 0;
while ($num < 1000) {
$num++;
if (($num % 2) == 0) continue;
echo "$num ";
}
echo "\n";
?>
while
loop. if (($num % 2) == 0) continue;If the expression $num % 2 returns 0, the number in question can be divided by 2.
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.
0 comments:
Post a Comment