if,elseif ... else和switch语句用于根据不同的条件做出决定.
您可以在代码中使用条件语句来做出决定. PHP支持以下三个决策制定语句 :
if ... else statement : 如果你想在条件为真时执行一组代码而使用另一条代码,如果条件不为真,则使用此语句
elseif statement : 与if ... else语句一起使用,以便在多个条件中的一个为真时执行一组代码
switch语句 : 如果要选择要执行的许多代码块之一,请使用Switch语句. switch语句用于避免if..elseif..else代码的长块.
If ... Else Statement
如果要在条件为真时执行某些代码,而在条件为假的情况下执行其他代码,请使用if .... else语句.
语法
if (condition) code to be executed if condition is true;else code to be executed if condition is false;
示例
以下示例将输出"周末愉快!"如果当天是星期五,否则,它将输出"祝你有个美好的一天!":
它将产生以下结果 :
Have a nice weekend!
ElseIf语句
如果您想要执行某些代码,如果其中一个条件为真,请使用elseif声明
语法
if (condition) code to be executed if condition is true;elseif (condition) code to be executed if condition is true;else code to be executed if condition is false;
示例
以下示例将输出"周末愉快!"如果当天是星期五,并且"祝周日愉快!"如果当天是星期天.否则,它将输出"祝你有愉快的一天!" :
它将产生以下结果 :
Have a nice Weekend!
Switch语句
如果要选择要执行的多个代码块之一,请使用Switch声明.
switch语句用于避免if..elseif..else代码的长块.
语法
switch (expression){ case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2;}
示例
开关语句以不寻常的方式工作.首先,它评估给定的表达式,然后寻找一个标签来匹配结果值.如果找到匹配值,则将执行与匹配标签关联的代码,或者如果没有标签匹配,则语句将执行任何指定的默认代码.
它将产生以下结果 :
Today is Monday