What Kind Of Control Structure Can Be Found In The Image Below?
Read Time: 12 mins Languages:
Today, we're going to discuss control structures and loops in PHP. I'll show you how to apply all the principal control structures that are supported in PHP, similar if, else, for, foreach, while, and more.
What Is a Command Structure?
In uncomplicated terms, a control structure allows you to control the flow of code execution in your awarding. By and large, a program is executed sequentially, line by line, and a control structure allows you to alter that flow, commonly depending on certain weather condition.
Control structures are cadre features of the PHP linguistic communication that let your script to reply differently to dissimilar inputs or situations. This could allow your script to give unlike responses based on user input, file contents, or some other data.
The post-obit flowchart explains how a control structure works in PHP.
As you can see in the higher up diagram, first a condition is checked. If the condition is truthful, the conditional code will be executed. The important thing to note here is that code execution continues normally after conditional lawmaking execution.
Let'southward consider the post-obit example.
In the above example, the program checks whether or not the user is logged in. Based on the user's login status, they will be redirected to either theLogin page or theMy Business relationship page. In this case, a control structure ends code execution by redirecting users to a different page. This is a crucial ability of the PHP linguistic communication.
PHP supports a number of different command structures:
-
if
-
else
-
elseif
-
switch
-
while
-
do-while
-
for
-
foreach
- and more
Let'south take a wait at a few of these control structures with examples.
Learning PHP Command Structures
In the previous department, nosotros learned the nuts of control structures in PHP and their usefulness in awarding evolution. In this section, we'll go through a couple of important control structures that you'll end upwardly using frequently in your day-to-day awarding development.
PHP If Statement
Theif
construct allows yous to execute a piece of code if the expression provided forth with it evaluates to true.
Let's have a expect at the following example to empathise how it actually works.
<?php $age = 50; if ($age > xxx) { repeat "Your age is greater than 30!"; } ?>
The above case should output theYour age is greater than 30!
message since the expression evaluates to true. In fact, if yous want to execute only a single statement, the to a higher place example can be rewritten without brackets, as shown in the following snippet.
<?php $age = 50; if ($age > 30) repeat "Your historic period is greater than 30!"; ?>
On the other hand, if you have more than than one argument to execute, y'all must use brackets, as shown in the following snippet.
<?php if (is_array($user)) { $user_id = isset($user['user_id']) ? $user['user_id'] : ''; $username = isset($user['username']) ? $user['username'] : ''; // and more statements... } ?>
PHP Else Statement
In the previous department, nosotros discussed theif
construct, which allows you to execute a piece of code if the expression evaluates to true. On the other hand, if the expression evaluates to faux, it won't do annihilation. More often than non, you also want to execute a unlike code snippet if the expression evaluates to simulated. That'southward where theelse
statement comes into the movie.
You always utilise theelse
argument in conjunction with anif
statement. Basically, yous can define information technology as shown in the following pseudo-code.
if (expression) { // code is executed if the expression evaluates to TRUE } else { // lawmaking is executed if the expression evaluates to Simulated }
Let'southward revise the previous example to empathize how it works.
<?php $age = l; if ($historic period < thirty) { echo "Your age is less than 30!"; } else { repeat "Your age is greater than or equal to xxx!"; } ?>
So when you lot have two choices, and one of them must be executed, you tin can apply theif-else
construct.
PHP Else If Statement
We tin consider theelseif
statement equally an extension to theif-else
construct. If y'all've got more than two choices to cull from, y'all can employ theelseif
statement.
Let's study the basic construction of theelseif
argument, every bit shown in the post-obit pseudo-code.
if (expression1) { // code is executed if the expression1 evaluates to Truthful } elseif (expression2) { // code is executed if the expression2 evaluates to TRUE } elseif (expression3) { // lawmaking is executed if the expression3 evaluates to TRUE } else { // code is executed if the expression1, expression2 and expression3 evaluates to Faux, a default pick }
Again, let'due south endeavor to understand it using a real-globe example.
<?php $age = 50; if ($historic period < 30) { echo "Your age is less than thirty!"; } elseif ($age > thirty && $age < 40) { echo "Your historic period is between 30 and xl!"; } elseif ($age > forty && $historic period < l) { echo "Your age is between 40 and 50!"; } else { echo "Your age is greater than 50!"; } ?>
As you tin can see in the above example, we have multiple weather condition, so we've used a series ofelseif
statements. In the event that allif
conditions evaluate to imitation, it executes the lawmaking provided in the lastelse
argument.
PHP Switch Argument
The switch statement is somewhat similar to theelseif
statement which we've just discussed in the previous section. The only difference is the expression which is beingness checked.
In the case of theelseif
statement, you have a set of different conditions, and an advisable action will be executed based on a condition. On the other hand, if you want to compare a variable with different values, yous tin can use theswitch
statement.
As usual, an example is the best way to understand theswitch
statement.
<?php $favourite_site = 'Code'; switch ($favourite_site) { instance 'Concern': echo "My favourite site is business concern.tutsplus.com!"; suspension; case 'Code': echo "My favourite site is lawmaking.tutsplus.com!"; break; instance 'Web Design': echo "My favourite site is webdesign.tutsplus.com!"; break; case 'Music': echo "My favourite site is music.tutsplus.com!"; break; case 'Photography': echo "My favourite site is photography.tutsplus.com!"; break; default: echo "I like everything at tutsplus.com!"; } ?>
Equally you can encounter in the above case, we desire to check the value of the$favourite_site
variable, and based on the value of the$favourite_site
variable, we want to print a bulletin.
For each value y'all want to bank check with the$favourite_site
variable, you have to ascertain thecase
cake. If the value is matched with a case, the code associated with that case cake volition be executed. After that, y'all need to utilize thesuspension
argument to stop lawmaking execution. If y'all don't employ theinterruption
statement, script execution will be continued up to the last block in the switch statement.
Finally, if you desire to execute a piece of code if the variable's value doesn't match any case, you can define it nether thedefault
block. Of class, it's non mandatory—information technology'due south just a mode to provide adefault case.
So that'southward the story of provisional control structures. We'll discuss loops in PHP in the side by side department.
Loops in PHP
Loops in PHP are useful when you lot want to execute a piece of code repeatedly until a condition evaluates to faux. So code is executed repeatedly equally long as a status evaluates to true, and as before long as the condition evaluates to simulated, the script continues executing the code after the loop.
The following flowchart explains how loops work in PHP.
Equally y'all tin meet in the above screenshot, a loop contains a condition. If the condition evaluates to true, the conditional code is executed. Later on execution of the provisional code, control goes dorsum to the loop status, and the flow continues until the condition evaluates to faux.
In this section, we'll go through the different types of loops supported in PHP.
While Loop in PHP
Thewhile
loop is used when you want to execute a piece of code repeatedly until thewhile
condition evaluates to false.
You can ascertain information technology every bit shown in the following pseudo-code.
while (expression) { // code to execute as long equally expression evaluates to TRUE }
Let's accept a look at a real-world example to understand how thewhile
loop works in PHP.
<?php $max = 0; echo $i = 0; repeat ","; echo $j = 1; repeat ","; $result=0; while ($max < 10 ) { $result = $i + $j; $i = $j; $j = $effect; $max = $max + i; echo $upshot; echo ","; } ?>
If you're familiar with the Fibonacci series, y'all might recognize what the higher up program does—information technology outputs the Fibonacci series for the get-go ten numbers. Thewhile
loop is more often than not used when you don't know the number of iterations that are going to take identify in a loop.
Do-While Loop in PHP
Thedo-while
loop is very similar to thewhile
loop, with the only difference being that the while condition is checked at the end of the first iteration. Thus, we tin guarantee that the loop code is executed at least one time, irrespective of the result of the while expression.
Let'due south have a look at the syntax of thepractise-while
loop.
exercise { // code to execute } while (expression);
Allow'southward go through a real-world to sympathise possible cases where you tin can utilise thedo-while
loop.
<?php $handle = fopen("file.txt", "r"); if ($handle) { do { $line = fgets($handle); // process the line content } while($line !== false); } fclose($handle); ?>
In the in a higher place example, we're trying to read a file line by line. Firstly, we've opened a file for reading. In our case, we're non sure if the file contains whatsoever content at all. Thus, we need to execute thefgets
role at least once to check if a file contains any content. Then nosotros tin utilise thedo-while
loop hither.do-while
evaluates the statusafter the showtime iteration of the loop.
For Loop in PHP
More often than not, thefor
loop is used to execute a slice of lawmaking a specific number of times. In other words, if you already know the number of times you lot want to execute a block of code, it's thefor
loop which is the best selection.
Permit's have a look at the syntax of thefor
loop.
for (expr1; expr2; expr3) { // lawmaking to execute }
Theexpr1
expression is used to initialize variables, and information technology's always executed. Theexpr2
expression is also executed at the kickoff of a loop, and if information technology evaluates to true, the loop code is executed. Afterwards execution of the loop lawmaking, theexpr3
is executed. By and large, theexpr3
is used to alter the value of a variable which is used in theexpr2
expression.
Let'due south go through the following example to see how it works.
<?php for ($i=one; $i<=10; ++$i) { echo sprintf("The square of %d is %d.</br>", $i, $i*$i); } ?>
The to a higher place plan outputs the foursquare of the first ten numbers. Information technology initializes$i
to 1, repeats as long as$i
is less than or equal to ten, and adds 1 to$i
at each iteration.
For Each in PHP
Theforeach
loop is used to iterate over array variables. If you accept an assortment variable, and yous want to become through each element of that array, theforeach
loop is the best pick.
Permit'southward have a look at a couple of examples.
<?php $fruits = array('apple', 'banana', 'orange', 'grapes'); foreach ($fruits as $fruit) { repeat $fruit; echo "<br/>"; } $employee = array('name' => 'John Smith', 'age' => thirty, 'profession' => 'Software Engineer'); foreach ($employee as $primal => $value) { echo sprintf("%south: %southward</br>", $fundamental, $value); echo "<br/>"; } ?>
If you want to access assortment values, you lot tin use the first version of theforeach
loop, as shown in the in a higher place example. On the other hand, if you lot want to access both a central and a value, yous can do it as shown in the$employee
case above.
Breaking Out of the Loop
There are times when y'all might want to break out of a loop before it runs its grade. This tin can be achieved easily using thepause
keyword. It volition become you out of the currentfor
,foreach
,while
,do-while
, orswitch
structure.
You can also employbreak
to become out of multiple nested loops past supplying a numeric argument. For case, usingbreak 3
will pause y'all out of 3 nested loops. Nevertheless, yous cannot pass a variable as the numeric argument if you lot are using a PHP version greater than or equal to 5.four.
<?php echo 'Simple Break'; for($i = 1; $i <= 2; $i++) { echo "\n".'$i = '.$i.' '; for($j = i; $j <= 5; $j++) { if($j == 2) { break; } echo '$j = '.$j.' '; } } /* Simple Interruption i = one j = one i = 2 j = 1 */ echo 'Multi-level Break'; for($i = 1; $i <= 2; $i++) { repeat "\n".'$i = '.$i.' '; for($j = i; $j <= v; $j++) { if($j == 2) { break 2; } echo '$j = '.$j.' '; } } /* Multi-level Suspension i = 1 j = one */ ?>
Another keyword that can interrupt loops in PHP iscontinue
. All the same, this only skips the rest of the current loop iteration instead of breaking out of the loop altogether. Merely likebreak
, you lot tin can also utilise a numerical value withgo along
to specify how many nested loops it should skip for the current iteration.
<?php repeat 'Simple Keep'; for($i = 1; $i <= two; $i++) { echo "\north".'$i = '.$i.' '; for($j = 1; $j <= five; $j++) { if($j == 2) { continue; } repeat '$j = '.$j.' '; } } /* Simple Continue i = 1 j = 1 j = iii j = 4 j = v i = 2 j = one j = three j = 4 j = 5 */ repeat 'Multi-level Continue'; for($i = 1; $i <= 2; $i++) { echo "\due north".'$i = '.$i.' '; for($j = 1; $j <= five; $j++) { if($j == ii) { continue 2; } echo '$j = '.$j.' '; } } /* Multi-level Continue i = 1 j = ane i = two j = i */ ?>
Conclusion
In this article, nosotros discussed dissimilar control structures and loops in PHP. They are an essential part of PHP—or any programming linguistic communication for that matter.
Learn PHP With a Gratuitous Online Course
If you desire to learn PHP, check out our free online course on PHP fundamentals!
In this class, you'll learn the fundamentals of PHP programming. Yous'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then yous'll build upwardly to coding classes for simple object-oriented programming (OOP). Along the way, you'll acquire all the most important skills for writing apps for the web: you'll get a chance to do responding to Get and Mail service requests, parsing JSON, authenticating users, and using a MySQL database.
Did you find this mail service useful?
What Kind Of Control Structure Can Be Found In The Image Below?,
Source: https://code.tutsplus.com/tutorials/php-control-structures-and-loops--cms-31999
Posted by: carusoagied2001.blogspot.com
0 Response to "What Kind Of Control Structure Can Be Found In The Image Below?"
Post a Comment