PHP If-Else,Switch Case和速记三元运算符示例

时间:2020-02-23 14:42:01  来源:igfitidea点击:

有时我们需要根据决策执行不同的操作,PHP提供了一些可用于此的条件语句。

  • if语句–仅在条件为true时才需要执行代码时使用。

  • If-Else语句–用于在条件为true时执行一段代码,在条件为false时执行另一段代码。

  • If-Else-If语句–如果可以根据条件执行多个代码,则在条件之一为真且其代码块被执行后,便会使用控制语句。

  • Switch语句–与if-else-if语句相同,但是它使代码更清晰。

  • 三元运算符–三元运算符提供了一种编写上述所有条件语句的简便方法。
    如果条件不是很复杂,最好使用三元运算符来减少代码大小,但是对于更复杂的条件,可能会造成混淆。
    语法是(Condition)? <Condition = True>:<Condition = False>

这是一个PHP脚本示例,显示了所有条件语句的用法,并使用三元运算符以非常小的代码大小实现了相同的逻辑。

<?php

$a=15;
$str="David";
$str1="hyman";
$color="Red";

//if condition example
if($a==15){
	echo "value of a is 15";
	echo "<br>";
}

//if-else condition example
if($str1 == "hyman"){
	echo "Hi hyman";
	echo "<br>";
}else {
	echo "Hi There!";
	echo "<br>";
}

//if-else-if example

if($str == "hyman"){
	echo "Hi hyman";
	echo "<br>";
}else if($str == "David"){
	echo "Hi David";
	echo "<br>";
} else{
	echo "Hi There!";
	echo "<br>";
}

//switch statement example

switch ($color){
	case "Red":
		echo "Red Color";
		break; //for breaking switch condition
	case "Green":
		echo "Green Color";
		break;
	default:
		echo "Neither Red or Green Color";
}
echo "<br>";

//PHP ternary operator example

//implementing the above if example with ternary operator
echo ($a == 15) ? "value of a is 15"."<br>":"";

//implementing the above if-else example with ternary operator
echo ($str1 == "hyman") ? "Hi hyman"."<br>" : "Hi There!"."<br>";

//implementing above if-else-if example with ternary operator
echo ($str == "hyman") ? "Hi hyman"."<br>" : (($str == "David") ? "Hi David"."<br>" : "Hi David"."<br>");

//implementing switch statement with ternary operator
echo ($color == "Red") ? "Red Color" : (($color == "Green") ? "Green Color" : "Neither Red or Green Color");
?>

上面的PHP脚本的输出是:

value of a is 15
Hi hyman
Hi David
Red Color
value of a is 15
Hi hyman
Hi David
Red Color