逻辑判断
PHP允许我们基于某种逻辑条件或比较条件执行操作。根据这些条件的结果,即,或者是真,或者是假,用户将按照要求执行操作。这就像一条双向的道路。如果你想要什么东西,那就走这边或者转那边。为了使用这个特性,PHP为我们提供了四个条件语句:
- if语句
- if…else语句
- if…elseif…else语句
- switch语句
现在让我们详细地看一下其中的每一个:
- if语句:这个语句允许我们设置一个条件。如果为真,将执行if子句中包含的以下代码块。
语法
123if (condition){// if TRUE then execute this code}
例子
1234567<?php$x = 12;if ($x > 0) {echo "The number is positive";}?>
输出
1The number is positive
流程图 - if…else语句:我们理解如果一个条件成立,即。,则if中的代码块将被执行。但如果条件不为真,我们想要执行一个操作,该怎么办?这就是其他方面发挥作用的地方。如果条件为真,则执行block,否则执行else block。
语法
123456if (condition) {// if TRUE then execute this code}else{// if FALSE then execute this code}例子
1234567891011<?php$x = -12;if ($x > 0) {echo "The number is positive";}else{echo "The number is negative";}?>输出
1The number is negative流程图
- if…else语句:这允许我们使用多个if…else语句。当有多个真实情况的条件时,我们使用这个。
语法
123456789101112if (condition) {// if TRUE then execute this code}elseif {// if TRUE then execute this code}elseif {// if TRUE then execute this code}else {// if FALSE then execute this code}例子
123456789101112131415<?php$x = "August";if ($x == "January") {echo "Happy Republic Day";}elseif ($x == "August") {echo "Happy Independence Day!!!";}else{echo "Nothing to show";}?>输出
1Happy Independence Day!!!流程图
- switch语句:“switch”在各种情况下执行,例如,它具有与条件匹配的各种情况,并适当地执行特定的情况块。它首先计算表达式,然后与每种情况的值进行比较。如果案例匹配,则执行相同的案例。要使用switch,我们需要熟悉两个不同的关键字,即break和default。
1.break语句用于停止自动控制流进入下一个情况并退出开关情况。
2.default语句包含如果没有匹配的情况下执行的代码。
语法
12345678910111213141516switch(n) {case statement1:code to be executed if n==statement1;break;case statement2:code to be executed if n==statement2;break;case statement3:code to be executed if n==statement3;break;case statement4:code to be executed if n==statement4;break;......default:code to be executed if n != any case;例子
1234567891011121314151617181920212223242526272829303132333435363738394041424344<?php$n = "February";switch($n) {case "January":echo "Its January";break;case "February":echo "Its February";break;case "March":echo "Its March";break;case "April":echo "Its April";break;case "May":echo "Its May";break;case "June":echo "Its June";break;case "July":echo "Its July";break;case "August":echo "Its August";break;case "September":echo "Its September";break;case "October":echo "Its October";break;case "November":echo "Its November";break;case "December":echo "Its December";break;default:echo "Doesn't exist";}?>输出
1Its February注意:case里面可以再嵌套判断,或者语句。
流程图
操作符
除了所有这些条件语句之外,PHP还提供了一种简写if…else语句的方法,称为三目运算符。该语句使用问号(?)和冒号(:),并接受三个操作数:一个要检查的条件,一个结果为真,一个结果为假。
语法
1 | (condition) ? if TRUE execute this : otherwise execute this; |
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php $x = -12; if ($x > 0) { echo "The number is positive \n"; } else { echo "The number is negative \n"; } // This whole lot can be written in a // single line using ternary operator echo ($x > 0) ? 'The number is positive' : 'The number is negative'; ?> |
输出
1 2 | The number is negative The number is negative |