Multiple nesting of if statements in PHP flow control
Classmate Wang Sixong We told in the first story that he has two secretaries: a life secretary and a work secretary.
Wang Sixong is also extremely well-planned in his travels and projects. He assigned business trips to his life secretary and work secretary respectively:
In life:
Check the weather first, bring rain gear and towel if it rains. Wear sunscreen if it’s not raining
The condition of rain gear, towels and sunscreen should be checked in advance. If not, buy them immediatelyAt work:
It is necessary to communicate in advance about the work plan before going to Dalian. When ready, it is necessary to check in time, check if it is qualified, and print and sign the form.
If not prepared in time, the main project communication topics should be listed.
Similar to the above situation, we need to use the if...elseif...else repeatedly nested structure.
One or more if statements can be nested in the if statement to realize the judgment of multiple parameters. This is the multiple nesting of if statements. Its structural form is as follows:
<?php if(判断1){ if(判断2){ 代码段 1 }else{ 代码段2 } }else{ if(判断3){ 代码段3 }else{ 代码段4 } } ?>
We use a flow chart to express it as follows:
Note:
- We are in code segments 1 and 2 , 3 and 4 can be added to the judgment. According to the actual situation, you can also add nesting
- Pay attention to the indentation. The function of indentation is only to make the code rich in layering, beautiful and easy to read, and has no impact on the generation of the target code.
We can use codes to express the life requirements of Mr. Wang Sixong in a nested structure. We used a three-level nested structure, and the code is as follows:
<?php //0表示工作秘书,1表示生活秘书 //用代码模拟随机产生当前的工作是生活秘书的还是工作秘书的 $mishu = rand(0,1); if($mishu){ //下雨和不下雨的状态,随机产生 //下雨状态为1 //不下雨状态为0 $xiyu = rand(0,1); if($xiyu){ //是否购买雨伞 $you = rand(0,1); if($you){ echo '下雨天,已购买不用买雨伞'; }else{ echo '下雨天,未购买,需要买雨伞'; } }else{ //是否购买防晒霜 $you = rand(0,1); if($you){ echo '没下雨,有防晒霜'; }else{ echo '没下雨,需要准备防晒霜'; } } }else{ //是否准备好了会议议程 $shifou = rand(0,1); if($shifou){ echo '已准备好,可以随时出发'; }else{ echo '没有准备好,需要打印,延迟出发'; } }
Warning: For novice programmers, please use caution when using this nested if...else loop. Because too many layers of loops can easily cause problems in the design logic, or there are too few braces, etc., which will lead to inexplicable problems in the program.
I hope you can write it out silently. Also, there cannot be a single grammatical error. In the future, we can use it at any time. If we want to react immediately in the brain, we can start writing.