Php 简明教程

PHP – Conditional Operators Examples

当需要根据条件设置值时,可以在 PHP 中使用条件运算符。它也被称为 ternary operator 。它首先评估一个表达式的真值或假值,然后根据评估结果执行给定的两个语句中的一个。

You would use conditional operators in PHP when there is a need to set a value depending on conditions. It is also known as ternary operator. It first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation.

三元运算符提供了一种简洁的方法来编写条件表达式。它们由三部分组成:条件、如果条件评估为真的返回值以及如果条件评估为假的返回值。

Ternary operators offer a concise way to write conditional expressions. They consist of three parts: the condition, the value to be returned if the condition evaluates to true, and the value to be returned if the condition evaluates to false.

Operator

Description

Example

? :

Conditional Expression

If Condition is true ? Then value X : Otherwise value Y

Syntax

其语法如下:

The syntax is as follows −

condition ? value_if_true : value_if_false

三元运算符特别适用于将 if-else 语句缩短为一行。可以使用三元运算符根据条件为变量分配不同的值,而无需多行代码。它可以提高代码的可读性。

Ternary operators are especially useful for shortening if-else statements into a single line. You can use a ternary operator to assign different values to a variable based on a condition without needing multiple lines of code. It can improve the readability of the code.

但是,您应明智地使用三元运算符,否则最终会使代码过于复杂,难以理解。

However, you should use ternary operators judiciously, else you will end up making the code too complex for others to understand.

Example

尝试以下示例以了解条件运算符在 PHP 中是如何工作的。复制并粘贴以下 PHP 程序到 test.php 文件中,并将其放在 PHP 服务器的文档根目录中,然后使用任何浏览器浏览它。

Try the following example to understand how the conditional operator works in PHP. Copy and paste the following PHP program in test.php file and keep it in your PHP Server’s document root and browse it using any browser.

<?php
   $a = 10;
   $b = 20;

   /* If condition is true then assign a to result otheriwse b */
   $result = ($a > $b ) ? $a :$b;

   echo "TEST1 : Value of result is $result \n";

   /* If condition is true then assign a to result otheriwse b */
   $result = ($a < $b ) ? $a :$b;

   echo "TEST2 : Value of result is $result";
?>

它将生成以下 output

It will produce the following output

TEST1 : Value of result is 20
TEST2 : Value of result is 10