当前位置:网站首页>Control structure (I)
Control structure (I)
2022-04-23 15:34:00 【Jimeng network worry free】
if sentence
while sentence
for sentence
foreach sentence
break sentence
if sentence
if Structure is a lot of languages, including PHP It's one of the most important features , It allows code snippets to execute conditionally .PHP Of if The structure and C Language is similar :
<?php
if ($a > $b)
echo "a is bigger than b";
else sentence
It is often necessary to execute a statement when a condition is met , When this condition is not met, other statements are executed , That's exactly what it is. else The function of .else Extended if sentence , Can be in if The value of the expression in the statement is FALSE Execute statement . For example, the following code is in a Greater than a Greater than b Time display a is bigger than b, On the contrary, it shows a is NOT bigger than b:
<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
else if sentence
You can also write elseif, As the name implies , yes if and else The combination of . and else equally , It extends if sentence , Can be in the original if Expression value is FALSE Execute different statements when . But and else The difference is , It's only in elseif The conditional expression value of is TRUE Execute statement . For example, the following codes will be displayed separately according to the conditions a is bigger than b,a equal to b perhaps a is smaller than b:
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
In the same if Statement can have more than one elseif part , The value of the first expression is TRUE( If any ) Of elseif Part will execute .
elseif The statement is only in the previous if And all the previous elseif The expression value of is FALSE, And the current elseif Expression value is TRUE When the .
Be careful : It must be noted that elseif And else if It is considered identical only if curly braces are used similar to the above example . If you use a colon to define if/elseif Conditions , Then you can't use two words else if, otherwise PHP There will be parsing errors .
<?php
/* Incorrect use : */
if($a > $b):
echo $a." is greater than ".$b;
else if($a == $b): // Will not compile
echo "The above line causes a parse error.";
endif;
/* Correct usage : */
if($a > $b):
echo $a." is greater than ".$b;
elseif($a == $b): // Pay attention to the use of a word elseif
echo $a." equals ".$b;
else:
echo $a." is neither greater than or equal to ".$b;
endif;
Alternative syntax for process control
PHP Provides some alternative syntax for process control , Include if,while,for,foreach and switch. The basic form of substitution grammar is to put the left curly bracket ({) Change it to a colon (:), Put the right curly bracket (}) Change to endif;,endwhile;,endfor;,endforeach; as well as endswitch;
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
Alternative grammar can also be used in else and elseif in . Here's an example that includes elseif and else Of if Examples of structures written in alternative grammatical formats :
<?php
if ($a == 5):
echo "a equals 5";
echo "...";
elseif ($a == 6):
echo "a equals 6";
echo "!!!";
else:
echo "a is neither 5 nor 6";
endif;
?>
Don't mix two grammars in the same control block .
while sentence
while loop yes PHP The simplest type of loop in . It and C In language while Behave the same .while The basic format of a statement is ( The code is in the syntax format , Not a code case , There is no need to hit the code ):
while (expr)
{
statement}
while The meaning of the sentence is very simple , It tells PHP as long as while The value of the expression is TRUE Repeat the nested loop statement . The value of the expression is checked every time the loop starts , So even if this value changes in the loop statement , The statement will not stop executing , Until the end of this cycle . Sometimes if while The value of the expression starts with FALSE, Then the loop statement will not be executed once .
and if The sentence is the same , Can be in while Enclose a statement group with curly braces in the loop , Or use alternative grammar :
while (expr):
statement
...
endwhile;
The following two examples are exactly the same , All display numbers 1 To 10:
<?php
/* example 1 */
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be $i before the increment (post-increment) */
}
/* example 2 */
$i = 1;
while ($i <= 10):
print $i;
$i++;
endwhile;
?>
do-while sentence
do-while Circulation and while The cycle is very similar , The difference is that the value of the expression is checked at the end of each loop, not at the beginning . And general while The main difference between loops is do-while The loop statement of is guaranteed to execute once ( The true value of the expression is checked at the end of each loop ), However, in general while Not necessarily in the cycle ( The expression truth value is checked at the beginning of the loop , If you start with FALSE Then the whole cycle is terminated immediately ).
do-while There is only one syntax for loops :
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
The above cycle will run exactly once , Because after the first cycle , When checking the true value of an expression , Its value is FALSE($i No more than 0) And cause the loop to terminate . Senior C Language users may be familiar with a different language do-while Use circularly , Put the sentence in do-while(0) In , Use... Inside the loop break
Statement to end the execution loop . The following code snippet demonstrates this approach :
<?php
do {
if ($i < 5) {
echo "i is not big enough";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
echo "i is ok";
/* process i */
} while(0);
?>
If you can't understand it immediately, don't worry . Even without this “ characteristic ” You can also write powerful code to . since PHP 5.3.0 rise , You can also use goto
To jump out of the loop .
for sentence
for loop yes PHP The most complex loop structure in the world . Its behavior and C Language similarity . for The syntax of circulation is ( The code is in the syntax format , Not a code case , There is no need to hit the code ):
for (expr1; expr2; expr3)
{
statement}
The first expression (expr1) Evaluate unconditionally before the loop begins ( And implement ) once .
expr2 Evaluate before each cycle begins . If the value is TRUE, Then continue the cycle , Execute nested loop statements . If the value is FALSE, Then stop the cycle .
expr3 Evaluated after each loop ( And implement ).
Each expression can be empty or include multiple expressions separated by commas . expression expr2 in , All expressions separated by commas are evaluated , But only take the last result .expr2 Being empty means that it will loop indefinitely ( and C equally ,PHP Secretly think its value is TRUE). This may not be as useless as expected , Because I often want to use conditional break Statement to end the loop instead of for True value judgment of expression .
Consider the following example , They all display numbers 1 To 10:
<?php
/* example 1 */
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
/* example 2 */
for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}
/* example 3 */
$i = 1;
for (;;) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
/* example 4 */
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>
Of course , The first example looks the most concise ( Or someone thinks it's the fourth ), But users may find that in for Using empty expressions in a loop is convenient in many cases . PHP Colons are also supported for Alternative syntax for loops ( The code is in the syntax format , Not a code case , There is no need to hit the code ).
for (expr1; expr2; expr3):
statement;
...
endfor;
Sometimes it is often necessary to traverse the array like the following example :
<?php
/* * This array will change the values of some of its cells during traversal */
$people = Array(
Array('name' => 'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0; $i < sizeof($people); ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>
The above code may be slow to execute , Because we have to calculate the length of the array every time we loop . Because the length of the array is always the same , You can use an intermediate variable to store the array length to optimize instead of calling count():
<?php
$people = Array(
Array('name' => 'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0, $size = sizeof($people); $i < $size; ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>
foreach sentence
foreach Syntax structure provides a simple way to traverse an array .foreach Can only be applied to arrays and objects , If you try to apply variables of other data types , Or uninitialized variables will send an error message . There are two kinds of grammar
foreach (array as $value)
statement
foreach (array as $key => $value)
statement
The first format traverses a given array Array . In each cycle , The value of the current cell is assigned to $value And the pointer inside the array moves one step forward .
The second format does the same thing , Only the key name of the current cell is assigned to the variable in each loop $key.
Change the value of an element
stay foreach There are two ways to change the value of an element
stay $value And before & To modify the elements of an array .
adopt $key Reassign .
edit /home/project/foreach.php
<?php
$arr1 = $arr2 = [1, 2, 3, 4];
foreach ($arr1 as &$value) {
$value = $value * 2;
}
var_dump($arr1, $value);
foreach ($arr2 as $key => $value) {
$arr2[$key] = $value * 2;
}
var_dump($arr2, $value);
perform
php foreach.php
It can be seen from the results , Of the last element of the array $value Reference in foreach It will remain after the cycle . It is recommended to use unset() To destroy it .
break sentence
break End the present for,foreach,while,do-while perhaps switch The execution of the structure . break You can accept an optional numeric parameter to decide how many cycles to jump out of .
edit /home/project/break.php
<?php
$i = 0;
while (++$i) {
for ($j = 0;$j < 10;$j++) {
switch ($i) {
case 1:
echo "At 1".PHP_EOL;
break 2;
case 5:
echo "At 5".PHP_EOL;
break 2;
case 10:
echo "At 10; quitting".PHP_EOL;
break 3;
default:
break;
}
}
}
perform
php break.php
As you can see from the results ,break With parameters, you can specify how many cycles to jump out .
版权声明
本文为[Jimeng network worry free]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231526352579.html
边栏推荐
- Sword finger offer (1) -- for Huawei
- MySQL Basics
- TLS / SSL protocol details (28) differences between TLS 1.0, TLS 1.1 and TLS 1.2
- About UDP receiving ICMP port unreachable
- My raspberry PI zero 2W toss notes to record some problems and solutions
- 编译,连接 -- 笔记
- Adobe Illustrator menu in Chinese and English
- Detailed explanation of MySQL connection query
- Elk installation
- 机器学习——逻辑回归
猜你喜欢
随机推荐
Pytorch中named_parameters、named_children、named_modules函数
Node. JS ODBC connection PostgreSQL
My raspberry PI zero 2W toss notes to record some problems and solutions
HJ31 单词倒排
Elk installation
fatal error: torch/extension. h: No such file or directory
Mysql连接查询详解
PHP 的运算符
让阿里P8都为之着迷的分布式核心原理解析到底讲了啥?看完我惊了
使用 Bitnami PostgreSQL Docker 镜像快速设置流复制集群
kubernetes之常用Pod控制器的使用
c语言---字符串+内存函数
MySQL InnoDB transaction
Introduction to dynamic programming of leetcode learning plan day3 (198213740)
Educational Codeforces Round 127 A-E题解
[backtrader source code analysis 18] Yahoo Py code comments and analysis (boring, interested in the code, you can refer to)
adobe illustrator 菜单中英文对照
重定向和请求转发详解
木木一路走好呀
ICE -- 源码分析